前言回顾:
基本的处理html数据的工具
- requests:可以发送数据和一些基本数据的处理方式 参考文献:https://editor.csdn.net/md/?articleId=118095431
- BeautifulSoup
- 正则表达式的使用 参考文献;https://editor.csdn.net/md/?articleId=117717623
文章目录
Xpath处理数据
- 前言回顾:
- 基本的处理html数据的工具
- Xpath处理数据
- 实例分析
# 导入模块
from lxml import etree
html = etree.parse('./test.html'(可以换成requests得到的数据包), etree.HTMLParser())
# 获取整个html代码
result = etree.tostring(html)
# 获取当前目录的所有节点
# html.xpath('//*')
# 获取子孙节点
# html.xpath("//")
# 获取子节点
# html.xpath("/")
result = html.xpath('/html//li/a')
for item in result:
print(item)
# 通过属性来获取值
result2 = html.xpath('//li[@class="item-3"]')
print(result2)
# 获取父节点
result1 = html.xpath('//a[@href="https://hao.360.cn/?a1004"]/../@class')
print(result1)
# 获取文本信息
result3 = html.xpath('//li/a[@href="https://hao.360.cn/?a1004"]/text()')
print(result3)
# 属性多个值匹配
result4 = html.xpath('//li[contains(@class,"sp")]/a/text()')
print(result4)
# 多个属性共同匹配
result5 = html.xpath('//li[contains(@class,"sp" and @name="123")]/a/text()')
# 根据顺序来选择
result6 = html.xpath("//li[2]")
# last()表示最后一个,last()-1表示倒数第二个,position()
关注
打赏