xpath的语法:
- 路径查询
// 查找所有的子孙节点,不考虑层级。
/ 找直接子节点
./a/@href 当前路径
../span/text() 父级下的span的文本内容
/* 任意一个子节点
//* 任意的子孙节点
- 谓语查询
//div[@id] 查找包含所有id属性的div节点
//div[@id='maincontent'] 查找id属性值为maincontent的div节点
- 属性查询
//@class 查找出所有的class属性
- 逻辑查询
//div[@id='head' and @class ='s_down'] 查找所有id属性等于head并且class属性等于s_down的div标签
//title | //price 选取文档中的所有 title 和 price 元素。注意: “|”两边必须是完整的xpath路径
eg. //book/letter/author
//book/letter/price
//book/letter/author | //book/letter/price
- 模糊查询
//div[contains(@id,'he')] 查询所有id属性包含he的div节点
//div[starts-with(@id,'he')] 查询所有id属性中以he做开头的的div属性
//div[ends-with(@id,'he')] 查询所有id属性中以he结尾的div属性
//ul/li/[last()]/a/@href ul中最后一个li内的a元素的href属性值
//ul/li[-2]/a/@href 所有ul标签中的倒数第二个li标签中的a的href的属性值
- 内容查询
//div/h1/text() 查找所有div标签下的直接子节点h1的内容
xpath的使用
安装lxml库
pip install lxml
安装xpath插件
1、chrome 安装
2、ctrl+shift+x 打开控制台
3、shift+选择网页内容
使用示例
# 导入lxml.etree
from lxml import etree
# etree.parse,对html文件的解析
html_tree=etree.parse('XX.html')
# etree.HTML(),对字符串的解析
html_etree=etree.HTML(response.read().decode('utf-8'))
html_tree.xpath('//a/@href') #根据xpath规则来解析html_tree
使用xpath路径查询信息,返回一个列表
from lxml import etree
html = '<div><a><img src="a.jpg"></a></div>'
html_tree = etree.HTML(html)
list = html_tree.xpath('//div//img/@src')
print(list)
对于连接查询的写法(示例,其中.必写,代表当前的xpath下的xpath)
with open('wyy/'+f'wangyiyun{page}.html','rb') as f:
html=f.read()
et=etree.HTML(html)
total=et.xpath("//div[@class='uc-ykt-coursecard-wrap_box']")
for x in total:
src_=x.xpath('.//img/@src')[0]
name=x.xpath("./div[@class='uc-ykt-coursecard-wrap_orgName f-fs0 f-thide']/text()")[0]
name=name.replace('\n','')