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)
相关推荐
m0_748232392 分钟前
基于OpenCV和Python的人脸识别系统_django
python·opencv·django
dme.27 分钟前
Python爬虫selenium验证-中文识别点选+图片验证码案例
爬虫·python
东方-教育技术博主31 分钟前
wps中zotero插件消失,解决每次都需要重新开问题
python
镰圈量化1 小时前
当电脑上有几个python版本Vscode选择特定版本python
开发语言·vscode·python
宇努力学习1 小时前
如何本地部署seepseek
python·ai·ollama·deepseek
橙狮科技1 小时前
使用 GPTQ 进行 4 位 LLM 量化
人工智能·python·语言模型
开开心心就好1 小时前
娱乐使用,可以生成转账、图片、聊天等对话内容
windows·python·智能手机·软件工程·娱乐·软件需求
愚昧之山绝望之谷开悟之坡1 小时前
ragflow-RAPTOR到底是什么?请通俗的解释!
python
B站计算机毕业设计超人1 小时前
计算机毕业设计Hadoop+Spark+DeepSeek-R1大模型民宿推荐系统 hive民宿可视化 民宿爬虫 大数据毕业设计(源码+LW文档+PPT+讲解)
大数据·hadoop·爬虫·机器学习·课程设计·数据可视化·推荐算法
背太阳的牧羊人2 小时前
RAG检索中使用一个 长上下文重排序器(Long Context Reorder) 对检索到的文档进行进一步的处理和排序,优化输出顺序
开发语言·人工智能·python·langchain·rag