'''
需求
爬取彼岸图网10页图片保存到本地
1: 找到每一页的url
https://pic.netbian.com/index_2.html
https://pic.netbian.com/index_7.html
get请求的html响应数据
翻页的规律是index_page依次递增的 翻页规律是从2开始的第一页就是index
2:发起请求获取响应
3: 解析列表页数据 使用xpath解析数据 取出详情页的url
4:获取详情页的响应 取出大图的下载链接
5:下载保存到本地
列表页是保存了每一条数据 看到是缩略图
如果想要爬大图 需要去到图片的详情页 这个里面有大图
'''
from lxml import etree
import requests
import re
headers1 = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
}
def main():
# 循环生成每一页的url
for page in range(1, 11):
if page == 1: # 判断一下 第一页的url是index.html
url = "https://pic.netbian.com/index.html"
else:
url = f"https://pic.netbian.com/index_{page}.html"
response = requests.get(url=url,headers=headers1)
response.encoding = "gbk"
tree = etree.HTML(response.text) # 打印的response。text 本地获取的响应
# 爬虫使用xpath解析的是本地的响应 爬虫请求得到的网络面板的资源响应数据 不是元素面板的
# 元素面板拿到的是页面加载完的数据 我们以网络面板的为准
# print(response.text)
li_list = tree.xpath('//ul[@class="clearfix"]/li')
for li in li_list:
detail_url = li.xpath('./a/@href')[0] # 取出详情页的url
# 拼接得到完整的链接
detail_url1 = "https://pic.netbian.com/"+detail_url
# print(detail_url1)
detail_response = requests.get(url=detail_url1,headers=headers1)
detail_response.encoding = "gbk"
# 请求得到详情页的响应
detail_tree = etree.HTML(detail_response.text) # 解析详情页的响应
image_url = detail_tree.xpath('//a[@id="img"]/img/@src')[0] # 取出图片下载链接
image_url1 = "https://pic.netbian.com"+image_url # 拼接得到完整的链接
image_title = detail_tree.xpath('//a[@id="img"]/img/@title')[0] # 取出图片标题
# 正则替换 把特殊字符处理一下
image_title = re.sub('[\\\\/:*?\"<>|]', '', image_title)
# print(image_url1,image_title)
save_image(image_url1,image_title)
def save_image(image_url1,image_title):
# 图片保存
image_content = requests.get(url=image_url1, headers=headers1).content # 获取图片的二进制数据
with open(f'./image/{image_title}.jpg', 'wb')as f:
f.write(image_content)
print(f'============={image_title}下载成功============')
main()
07-08
1413
1413
05-16

被折叠的 条评论
为什么被折叠?



