python爬取网站图片案例

下载指定页的图片Get方式

# _*_ coding : utf-8 _*_
# @Time : 2023/9/6 9:50
# @Author : xiaoyu
# @File : 爬取表情包
# @Project : basic


import urllib.request
from lxml import etree


def get_request(page):
    if (page == 1):
        url = "https://sc.chinaz.com/tupian/keaitupian.html"
    else:
        url = "https://sc.chinaz.com/tupian/keaitupian_" + 'str(page)' + ".html"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69'
    }
    request = urllib.request.Request(url=url, headers=headers)
    return request


def get_resource(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode("utf-8")
    return content


# 一般设计图片的网站都会进行懒加载一般是 @src 需要根据要求去修改

def down_load(content):
    tree = etree.HTML(content)
    name_list = tree.xpath('//div[@class="item"]/img/@alt')
    img_list=tree.xpath('//div[@class="item"]/img/@data-original')
    for i in range(len(name_list)):
        name = name_list[i]
        src = img_list[i]
        url = 'https:' + src
        urllib.request.urlretrieve(url=url, filename='E:\\PythonProject\\basic\\宠物图片\\' + name + '.jpg')


if __name__ == '__main__':
    start_page = int(input("请输入起始页码:"))
    end_page = int(input("请输入结束页码:"))
    for page in range(start_page, end_page + 1):
        # 定制请求对象
        request = get_request(page)
        # 获取网页源码
        content = get_resource(request)
        # 下载到本地
        down_load(content)

效果展示

在这里插入图片描述

xpath插件使用:ctrl + shift + x

1.安装lxml库
pip install lxml ‐i https://pypi.douban.com/simple
2.导入lxml.etree
from lxml import etree
3.etree.parse() 解析本地文件
html_tree = etree.parse(‘XX.html’)
4.etree.HTML() 服务器响应文件
html_tree = etree.HTML(response.read().decode(‘utf‐8’)
4.html_tree.xpath(xpath路径)
xpath基本语法:
1.路径查询
//:查找所有子孙节点,不考虑层级关系
/ :找直接子节点
2.谓词查询
//div[@id]
//div[@id=“maincontent”]
3.属性查询
//@class
4.模糊查询
//div[contains(@id, “he”)]
//div[starts‐with(@id, “he”)]
5.内容查询
//div/h1/text()
6.逻辑运算
//div[@id=“head” and @class=“s_down”]
//title | //price

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力奋斗的JAVA小余

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值