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)
相关推荐
YiSLWLL11 分钟前
使用Tauri 2.3.1+Leptos 0.7.8开发桌面小程序汇总
python·rust·sqlite·matplotlib·visual studio code
丰锋ff14 分钟前
爬虫学习总结
爬虫
花酒锄作田43 分钟前
[flask]自定义请求日志
python·flask
SsummerC2 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
Tandy12356_2 小时前
Godot开发2D冒险游戏——第一节:主角登场!
python·游戏引擎·godot
西柚小萌新3 小时前
【Python爬虫基础篇】--4.Selenium入门详细教程
爬虫·python·selenium
橘猫云计算机设计4 小时前
springboot基于hadoop的酷狗音乐爬虫大数据分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·hadoop·spring boot·爬虫·python·数据分析·毕业设计
YOULANSHENGMENG4 小时前
linux 下python 调用c++的动态库的方法
c++·python
SsummerC4 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
一眼青苔5 小时前
切割PDF使用python,库PyPDF2
服务器·python·pdf