爬彼岸图网

'''
    需求
        爬取彼岸图网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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>