0
点赞
收藏
分享

微信扫一扫

requests用parsel解析爬取网络图片

眸晓 2022-03-11 阅读 72
import requests
import parsel
import time
import os

start = time.time()     # 记录开始时间

# 判断文件是否存在
if not os.path.exists('./image'):
    # 创建文件
    os.mkdir('./image')

# 准备好url(网址)、headers(请求头)
url = "https://www.woyaogexing.com/touxiang/index_{0}.html"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"}

count = 1   # 记录爬取图片张数
# 分页
for i in range(2,6):
    # 请求
    response = requests.get(url=url.format(i), headers=headers)
    response.encoding = "utf-8"
    # 解析
    sel = parsel.Selector(response.text)
    # 提取数据
    divs = sel.css("div.pMain>.txList")
    for div in divs:
        # 二次解析
        title = div.css("a.img::attr(title)").get()  # 文件名
        img_url = div.css("a.img>img.lazy::attr(src)").get()  # 图片url
        img_url = "https:" + img_url
        suffix = img_url.split(".")[-1]  # 文件后缀
        path = "./image/" + title + "." + suffix  # 文件路径
        img_response = requests.get(url=img_url, headers=headers).content
        try:
            with open(path, "wb") as f:
                f.write(img_response)
                count += 1
                print("正在爬取第 {0} 页,文件保存成功:{1},已爬取 {2} 张".format(i, title, count))
        except Exception as e:
            print(e)
        time.sleep(0.5)
f.close()       # 关闭文件
end = time.time()   # 记录结束时间
print("已爬取 {0} 页,{1} 张图片,用时 {2} 秒,程序运行结束".format(i,count,end-start))

输出:

查看文件:

学会了之后再也不用担心没有头像换了。

打卡第62天,对python大数据感兴趣的朋友欢迎一起、讨论、交流,请多指教!

举报

相关推荐

0 条评论