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

效果如下:

相关推荐
黄贵根4 小时前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript
小趴蔡ha7 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534787 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
zzzll11117 小时前
Claude Code离线安装方案揭秘
开发语言·php
数字化转型分享点滴8 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03018 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比8 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
郝学胜-神的一滴8 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj9 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
tang777899 小时前
爬虫代理报错速查:407/408/409/410/503 从报错到根治(实测可用)
爬虫·爬虫代理·动态代理ip·代理ip·503·407·爬虫报错