Python爬虫系列-爬取百度贴吧图片

这是我新开的一个博客系列-Python爬虫,里面收集了我写过的一些爬虫脚本给大家参考,水平有限,不当之处请见谅。

这是我之前在CSDN问答贴中回答网友的问题:

(https://ask.csdn.net/questions/8042566?spm=1001.2014.3001.5505)

网友给了基础版,但是有问题,爬不出图片,我在他的基础上加入了header参数可以下载了。具体见如下源码:

python 复制代码
# 百度贴吧的图片下载
# 1.通过request拿到源代码数据
# 2.通过bs对源代码进行解析,拿到图片的urL
# 3.依次对图片地址发送请求
# 4.把图片内容写进文件中

import requests
from bs4 import BeautifulSoup as bs

header = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
          'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'Accept-Encoding':'gzip, deflate, br',
          'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
          'Host':'tieba.baidu.com'
          }
index_url = 'https://tieba.baidu.com/p/8783217764'
res= requests.get(url=index_url, headers=header)
soup = bs(res.content,"html.parser")
image_urls = soup.select("img.BDE_Image")
# print(response.content)

offset = 0
for image_url in image_urls:
    print(image_url['src'])
    image_content = requests.get(image_url['src']).content
    with open('{}.jpg'.format(offset), 'wb')as f:
        f.write(image_content)
    offset = offset + 1

效果如下:

相关推荐
OPEN-F7 分钟前
ROS2系列教程:tf2坐标变换详解(C++/Python)
开发语言·c++·python
2601_9620973612 分钟前
Python工作流实战:SpiffWorkflow深度应用与BPMN自动化指南
python·自动化·工作流·bpmn·spiffworkflow
XR12345678817 分钟前
医院基础网络改造升级选型深度解析
开发语言·网络·php
reasonsummer18 分钟前
【办公类-146-05】20260901《一分园、二分园四大教育》(优化版:标题excle+复制AI文字+Python占位符录入)
开发语言·数据库·c#
baopixiaoz35 分钟前
BeeQuant × BeeAgent:AI驱动智能交易
大数据·人工智能·python·区块链
名字还没想好☜39 分钟前
Go 标准库 flag 包实战:参数解析、子命令、自定义 Value 类型与默认值
开发语言·后端·golang·go
公爵爱学习44 分钟前
无人机定点飞行-介绍
开发语言·图像处理·python·学习·线性回归·无人机
stillstream_ink1 小时前
OpenCart UI 自动化测试实战:POM 四层架构 + 失败自动截图 + 飞书通知
python·测试
databook1 小时前
Beta 分布:如何用“成功”和“失败”来预测下次尝试
python·数据挖掘·数据分析
西西弗Sisyphus1 小时前
Qt 分类导航区的实现
开发语言·qt