爬取糗图百科图片

import requests
import re
import os
'''爬取糗事百科所有图片(利用re表达式)'''

# 如果目录不存在,则创建目录
if not os.path.exists('./pics'):
    os.makedirs('./pics')

headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
}
#  循环访问页数
for i in range(1,11):
    url="https://www.qiushibaike.com/imgrank/page/%d/"%(i)

    # 得到页面数据
    html_data=requests.get(url=url,headers=headers)
    html_text=html_data.text

    # 利用re表达式,得到图片网址
    ex='<img src="//pic.qiushibaike.com/system/pictures/(.*?)" alt='
    list_jpg=re.findall(ex,html_text,re.S)

    for jpg_url in list_jpg:
        # 生成图片名字
        jpg_name=jpg_url.split('/')[-1]
        # 合成图片网址
        jpg_url="https://pic.qiushibaike.com/system/pictures/"+jpg_url
        # 得到图片数据
        # text字符串 content 二进制数据 json对象
        jpg_response=requests.get(url=jpg_url,headers=headers).content
        # 二进制方式写入数据
        with open('./pics/'+jpg_name,'wb') as fp:
            fp.write(jpg_response)
            print(jpg_name,"success")

总结:注意content为二进制数据,写入图片用

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值