python抓取图片并本地存储

一、注意事项

1、抓取图片的代码较简单,有些网站拿到文字乱码,主要体现转化乱码的操作,encode(‘iso-8859-1’).decode(‘gbk’);
2、用xpath进行标签解析

二、源码

import requests
from lxml import etree
import os

# 第一页网址:http://pic.netbian.com/4kqiche/index.html
# 第二页开始的网址:http://pic.netbian.com/4kqiche/index_2.html

# 请求头
headers = {'User-Agent': 'Mozilla/5.0'}

# 新建存放图片文件夹
file_path = './pic'
if not os.path.exists(file_path):
    os.makedirs(file_path)
    
# 爬取前5页图片
for page in range(1, 6):
    if page == 1:
        url = 'http://pic.netbian.com/4kqiche/index.html'
    else:
        url = f'http://pic.netbian.com/4kqiche/index_{page}.html'
    # 获取网页源码
    resp = requests.get(url, headers=headers).text
    # xpath解析标签内容
    tree = etree.HTML(resp)
    li_list = tree.xpath('//ul[@class="clearfix"]/li')
    # 定位每张图片标签并解析
    for li in li_list:
        img_src = 'http://pic.netbian.com' + li.xpath('./a/img/@src')[0]
        img_name = li.xpath('./a/b/text()')[0]
        # 原始名称解析乱码,需转码
        img_name = img_name.encode('iso-8859-1').decode('gbk')
        img_save = requests.get(img_src, headers=headers).content
        # 保存图片
        with open(f'{file_path}/{img_name}.jpg', 'wb') as fp:
            fp.write(img_save)

感谢看到这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值