python利用urllib和xpath爬取并保存图片

概要

在网络时代,图片是信息传递的重要形式之一,而Python作为一种多用途的编程语言,可以用来编写爬虫从网页上获取图片,并保存到本地。本文将介绍如何使用Python爬虫实现这一功能,并探讨一些进阶技巧。

实现

(1)请求对象定制

python 复制代码
# 请求对象定制
def create_request(page):

    if 1 == page:
        url = 'https://sc.chinaz.com/tupian/huacaotupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/huacaotupian_' + str(page) + '.html'

    # 防止UA(User-Agent)检查
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
    }

    request = urllib.request.Request(url=url, headers=headers)
    return request

(2)获取网页源码

python 复制代码
# 获取网络源码
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content

(3)解析并下载图片

python 复制代码
# 下载
def down_load(content):
    tree = etree.HTML(content)
    name_list = tree.xpath('//div[@class="container"]//div/div/img/@alt')
    img_list = tree.xpath('//div[@class="container"]//div/div/img/@data-original')
    # for i in range(len(name_list)):
    #     print('name', i)
    # for i in range(len(img_list)):
    #     print('src', i)
    for i in range(len(name_list)):
        urllib.request.urlretrieve(url= 'https:' + img_list[i], filename='./out_Data/img/' + name_list[i] + '.png')

解析网页源码这里用到了xpath,xpath是lxml下的一个包,使用时,需要导入:

python 复制代码
from lxml import etree

完整代码

完整代码如下:

python 复制代码
import urllib.request
from lxml import etree

# 分析页码之间的关系
# get请求
# https://sc.chinaz.com/tupian/huacaotupian.html  1
# https://sc.chinaz.com/tupian/huacaotupian_2.html 2
# https://sc.chinaz.com/tupian/huacaotupian_3.html  3
# https://sc.chinaz.com/tupian/huacaotupian_4.html  4

# 请求对象定制
def create_request(page):

    if 1 == page:
        url = 'https://sc.chinaz.com/tupian/huacaotupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/huacaotupian_' + str(page) + '.html'

    # 防止UA(User-Agent)检查
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
    }

    request = urllib.request.Request(url=url, headers=headers)
    return request

# 获取网络源码
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content

# 下载
def down_load(content):
    tree = etree.HTML(content)
    name_list = tree.xpath('//div[@class="container"]//div/div/img/@alt')
    img_list = tree.xpath('//div[@class="container"]//div/div/img/@data-original')
    # for i in range(len(name_list)):
    #     print('name', i)
    # for i in range(len(img_list)):
    #     print('src', i)
    for i in range(len(name_list)):
        urllib.request.urlretrieve(url= 'https:' + img_list[i], filename='./out_Data/img/' + name_list[i] + '.png')



if __name__ == '__main__':
    start_page = int(input('请输入起始页码: '))
    end_page = int(input('请输入截止页码: '))
    for page in range(start_page, end_page + 1):
        print('下载至第' + page + '页')
        # 请求对象定制
        request = create_request(page)
        # 获取网页源码
        content = get_content(request)
        # 下载数据
        down_load(content)
相关推荐
打工仔折腾 AI几秒前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
信誓旦旦的程序猿1 小时前
【Python量化实战宝典 #21】北向资金跟随手册:聪明钱择时信号(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
严谨的麻辣烫1 小时前
静态 ISP 代理请求超时怎么排查?Python 与 curl 实战
python·http·requests·1024程序员节·网络排障
KeepRobots3 小时前
11-01 温哥华不回拨:用 60 行 Python 查你的工单系统会不会差一小时(KeepRobots 工程笔记)
python
xiao77mwq3 小时前
你以为 OCR 慢?实测 81.3 s 里全是故障代价:如何把「定格态」消掉,让耗时从 6.5 s 到 13 倍差距显出原形
python
深圳市益普科技有限公司3 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法
“AI国潮设计-小江”3 小时前
【AIGC实战】Python+SDXL打造“潮汕英歌舞IP”万能立牌插件,批量生成“发财元宝蛋糕”视觉营销方案(附源码)
开发语言·人工智能·python·prompt·aigc
砚底藏山河4 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融
十五年专注C++开发4 小时前
pybind11:一个跨C++和Python平台的编程库
开发语言·c++·python·pybind11
炘爚4 小时前
数据结构算法总结
数据结构·python·算法