【Python爬虫】爬取表情包-学习基本的页面爬取
本帖最后由 ◆ず简单↓。 于 2021-11-24 14:37 编辑static/image/hrline/4.gif 爬取表情包static/image/hrline/4.gif
一、爬取页面: https://fabiaoqing.com/biaoqing
二、能学到了什么(专业非Python:有错误请指正,看到会及时调整修改,还是比较适用于入门爬虫,基本上不是前后端分离的都可以使用)
[*]爬取 HTML 页面
[*]使用 XPath 语法解析页面
[*]asyncio 进行同步调用,防止爬取过快
[*]保存图片到文件夹
[*]简单的正则表达式,剔除 windows 不运行出现的字符
[*]定时器 time.sleep 延时
[*]etree 解析页面,基本上爬取页面都能这样用
[*]错误处理:错误重试,多次错误则跳过
[*]tqdm 进度条显示(用法在百度上面有很多 https://blog.csdn.net/qq_33472765/article/details/82940843)
https://www.dndn.top/static/image/hrline/4.gif 效果展示https://www.dndn.top/static/image/hrline/4.gif
static/image/hrline/4.gif 代码区域static/image/hrline/4.gif# -*- coding: utf-8 -*-
# Time : 2021/11/23 10:39
# AuThor : Melon
# site :
# note :
# file : Test.py
# Software: PyCharm
import asyncio
import os
import re
import time
import requests
from lxml import etree
from tqdm import tqdm
# 错误次数
err_num = 0
async def saveImg(image_url, file_name):
global err_num
# Windows 保存文件时不能出现这些字符,全部替换成_
file_name = re.sub(r'[\\/:*?"<>|\r\n]+', "_", file_name)
try:
# 文件夹名称
dir_name = '表情包'
# 没有文件夹 就 创建文件夹
if not os.path.exists(dir_name):
os.mkdir(dir_name)
# 加延迟防止过快
time.sleep(0.5)
result = requests.get(image_url)
# 保存图片
with open(dir_name + "/" + file_name, "wb") as f:
f.write(result.content)
except Exception as e:
# 异常:1.打印错误信息 2.延迟 3S 后重新调用 3.错误超过3次则跳过
err_num += 1
print("\nError Total %s Sleep 3 saveImg:%s Message: %s" % (err_num, image_url, e))
if err_num >= 3:
pass
else:
time.sleep(3)
await saveImg(image_url, file_name)
async def get_img(start_page, end_page):
global err_num
for i in range(start_page, end_page):
url = "https://fabiaoqing.com/biaoqing/lists/page/{}.html".format(i)
get = requests.get(url=url)
# xpath解析
html = etree.HTML(get.content)
divs = html.xpath("//div[@class='tagbqppdiv']")
# 设置进度条
pbar = tqdm(total=len(divs))
# 设置进度条前面的文字
pbar.set_description("Processing 第%s页" % i)
for div in divs:
# 设置进度条后面的文字
pbar.set_postfix_str(div.xpath("./a/img/@title"))
# 保存图片
err_num = 0
await saveImg(div.xpath("./a/img/@data-original"), div.xpath("./a/img/@title") + '.png')
# print('\n' + div.xpath("./a/img/@title"), div.xpath("./a/img/@data-original"))
# time.sleep(0.5)
# 更新进度条
pbar.update(1)
# 关闭进度条
pbar.close()
if __name__ == '__main__':
# 1. 创建一个事件循环
loop = asyncio.get_event_loop()
tasks = [
loop.create_task(get_img(1, 3)),
]
# 3. 执行事件队列
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
6666666666 谢谢分享 谢谢大牛 必须支持,谢谢分享 先收藏了,万一用到呢 正需要,支持楼主,在大牛我只看好你! 感谢楼主分享 11111
页:
[1]