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