Python爬虫之使用xpath进行HTML Document文档的解析

响应有两种:JSON数据和HTML页面,对于后者就需要进行解析HTML Documen得到我们需要的信息。

① xpath使用

可以提前安装xpath插件,也可以自己从HTML源码解析。

python 复制代码
(1)打开chrome浏览器
(2)点击右上角小圆点
(3)更多工具
(4)扩展程序
(5)拖拽xpath插件到扩展程序中
(6)如果crx文件失效,需要将后缀修改zip
(7)再次拖拽
(8)关闭浏览器重新打开
(9)ctrl + shift + x
(10)出现小黑框

1.安装lxml库

python 复制代码
pip install lxml ‐i https://pypi.douban.com/simple

2.导入lxml.etree

python 复制代码
from lxml import etree

3.etree.parse() 解析本地文件得到HTML Document

python 复制代码
html_tree = etree.parse('XX.html')

4.etree.HTML() 服务器响应文件得到HTML Document

python 复制代码
html_tree = etree.HTML(response.read().decode('utf‐8')

5.html_tree.xpath(xpath路径)解析目标信息

② 基本语法

xpath基本语法:

python 复制代码
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

③ xpath使用案例

查找ul下面的li

python 复制代码
# li_list = tree.xpath('//body/ul/li')

查找所有有id的属性的li标签

python 复制代码
# text()获取标签中的内容
# li_list = tree.xpath('//ul/li[@id]/text()')

找到id为l1的li标签 注意引号的问题

python 复制代码
# li_list = tree.xpath('//ul/li[@id="l1"]/text()')

查找到id为l1的li标签的class的属性值

python 复制代码
# li = tree.xpath('//ul/li[@id="l1"]/@class')

查询id中包含l的li标签

python 复制代码
# li_list = tree.xpath('//ul/li[contains(@id,"l")]/text()')

查询id的值以l开头的li标签

python 复制代码
# li_list = tree.xpath('//ul/li[starts-with(@id,"c")]/text()')

查询id为l1和class为c1的

python 复制代码
# li_list = tree.xpath('//ul/li[@id="l1" and @class="c1"]/text()')

li_list = tree.xpath('//ul/li[@id="l1"]/text() | //ul/li[@id="l2"]/text()')

# 判断列表的长度
print(li_list)
print(len(li_list))

获取class="week"的第一个dd的文本节点

java 复制代码
response = requests.get(url=url,headers=headers)
# print(response.text)
# print(response.content)
tree = html.fromstring(response.text)
# 这里得到的是一个数组
first_week_text_list = tree.xpath('//dl[@class="weather_info"]//dd[@class="week"][1]/text()')
if first_week_text_list:  # 检查是否找到了任何文本
    # 将所有文本节点合并成一个字符串并去除空白字符
    first_week_text = ''.join(first_week_text_list).strip()
    print(f"First week text: {first_week_text}")
else:
    print("No text found in the <dd> elements with class 'week'.")

④ 爬取站长素材情侣图片案例

python 复制代码
# (1) 请求对象的定制
# (2)获取网页的源码
# (3)下载
# 需求 下载的前十页的图片
# https://sc.chinaz.com/tupian/qinglvtupian.html   1
# https://sc.chinaz.com/tupian/qinglvtupian_page.html

import urllib.request
from lxml import etree

def create_request(page):
    if(page == 1):
        url = 'https://sc.chinaz.com/tupian/qinglvtupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/qinglvtupian_' + str(page) + '.html'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
    }

    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):
#     下载图片
    # urllib.request.urlretrieve('图片地址','文件的名字')
    tree = etree.HTML(content)

    name_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@alt')

    # 一般设计图片的网站都会进行懒加载
    src_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@data-original')

    for i in range(len(name_list)):
        name = name_list[i]
        src = src_list[i]
        url = 'https:' + src

        urllib.request.urlretrieve(url=url,filename='./loveImg/' + name + '.jpg')




if __name__ == '__main__':
    start_page = int(input('请输入起始页码'))
    end_page = int(input('请输入结束页码'))

    for page in range(start_page,end_page+1):
        # (1) 请求对象的定制
        request = create_request(page)
        # (2)获取网页的源码
        content = get_content(request)
        # (3)下载
        down_load(content)
相关推荐
Y幽谷客14 小时前
Python加载本地大模型(Qwen3.5 8B)
python·大模型
伞伞悦读15 小时前
【第36期】Python 目录与路径详解:pathlib、文件遍历、创建、复制、移动和删除风险
开发语言·python
线上放牧人15 小时前
Windows删除图标缓存
windows·python·pyqt
qq_54702617916 小时前
Python 变量和简单数据类型
python
智搜广告17 小时前
智搜广告:科技行业AI回答优化公司如何破局
大数据·python·elasticsearch·geo
IpdataCloud17 小时前
AI智能体调用工具怎么核验来源IP?归属地、网络类型与代理风险识别(含Python代码)
数据库·python·tcp/ip
2601_9669496518 小时前
只拿到股票代码还不够:量化程序到底还需要哪些标的信息?——从数据建模开始理解股票元数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
蒸鱼Yuzheng18 小时前
Python 游戏测试开发怎么准备:日志解析、接口校验、并发与可维护性
自动化测试·python·测试开发·面试题·游戏测试
Ivanqhz18 小时前
BM1688 双核架构
python·深度学习·神经网络·cnn·mlir
Java后端的Ai之路19 小时前
Python进阶探索17 - Python中的深拷贝与浅拷贝
人工智能·python·ai·浅拷贝·深拷贝