xpath解析图片 爬取图片到本地

爬取 https://pic.netbian.com/4kdongwu/ 中的图片,存储到本地。

难点:

1.获取图片地址后发送请求,响应对象为二进制格式的,要同content接收

2.写入图片用 'wb'

# 爬取 https://pic.netbian.com/4kdongwu/ 中的图片,存储到本地。
import requests
from lxml import etree
import os
if __name__ == '__main__':
    # 创建存爬取到照片的文件夹
    if not os.path.exists('./第三章:数据解析/code/biantu'):
        os.mkdir('./第三章:数据解析/code/biantu')
    
    url = 'https://pic.netbian.com/4kmeinv/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
    }
    # 网页源码
    response = requests.get(url, headers)
    # 设置响应对象的编码格式
    # response.encoding = 'gzip'
    response.encoding = response.apparent_encoding
    page_data = response.text
    etree = etree.HTML(page_data)
    # 获取对应的图片url列表
    photo_url_list = etree.xpath('//ul[@class="clearfix"]/li/a/img/@src')
    # 获取对应图片名称列表
    photo_name_list = etree.xpath('//ul[@class="clearfix"]/li/a/b/text()')
    #  使用迭代进行遍历 有索引
    for index in range(len(photo_url_list)):
        # 单个图片的请求地址
        photo_url = 'https://pic.netbian.com'+photo_url_list[index]
        # 单个图片的名称
        photo_name = photo_name_list[index]
        photo = requests.get(photo_url, headers).content
        # 调用open写入 注意写入规则是wb 二进制(图片)
        with open('./第三章:数据解析/code/biantu/'+photo_name+'.jpg', 'wb') as fp:
            fp.write(photo)
            print('爬取图片:'+photo_name+'   成功!')
    print('爬取结束!')

猜你喜欢

转载自blog.csdn.net/qq_38499019/article/details/115983722