爬虫学习之爬取百度贴吧照片

发布时间 2023-05-17 16:01:21作者: 慧眼识辰
1.通过requests拿到网页的源代码数据

导入requests和etree模块
import requests
from lxml import etree
 

2.通过lxml通过对源代码数据进行解析,拿到照片的URL地址

首先进行发送请求,获取URL
 index_url = 'https://tieba.baidu.com/p/7703334464'

 隐藏自己,使用headers,并使用get来请求,使用text响应文本内容。

 
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42'
}
response = requests.get(index_url, headers=headers).text
 

3.依次对照片地址发送网络请求

 使用etree模块xpath方法来对照片地址获取
re = etree.HTML(response)
image_urls = re.xpath('//img[@class="BDE_Image"]/@src')

 

4.把照片的原始内容写入照片文件

 定义offset来进行对照片保存时对名字的要求,获取每一张照片。通过for循环来进行对获取的照片URL进行依次操作。使用content来请求获取照片内容。
offset = 0

for image_url in image_urls:

    image_content = requests.get(image_url).content

    with open('./img/{}.jpg'.format(offset),'wb') as f:
        f.write(image_content)
        offset = offset + 1