python xpath语法总结
python xpath语法总结:
常用的:
//
1.从任意节点开始
/
2.从根节点开始
//div/p
3.div下的p标签
//div[@class="hrzz_bottom"]/ul/li/a/@href //div[@class="hrzz_bottom"]/ul/li/a/attribute::href
3.1 attribute 获取所有属性的值
//div[@class="hrzz_bottom"]/ul/li/a/attribute::href
4.1.li下的ahref属性即链接
//div[@class="hrzz_bottom"]//li/a/@title
4.2.li下的a链接title属性
//a[contains(@href,'tags.php')]/@href
4.3.所有包含tags.php的a链接
//p/text()
5.获取p标签下的文字
//div[@class="hrzz_bottom"]
6.class值为hrzz_bottom的div标签
//div[contains(@class,"hrzz_bottom")]
7.class值包含hrzz_bottom的div标签
//div[contains(@class, "show_content")]|//div[contains(@class,"hl_body")]
8.class值包含hrzz_bottom的div或者class值包含hl_body的div
//div[starts-with(@class,"show_")]
8.1 div class值开头包含show_
//div/p[3]
9.div下的第三个p标签
//div/p[position()>3]
10.从div下的第四个节点开始选
//div/p[last()]
10.1div下的最后一个p标签
//div/p/text()
11. 获取接点的文本
实例化对象
from lxml import etree doc = etree.HTML(html) title = doc.xpath('//div') for tr in trs: href=tr.xpath(".//a")
注意在trs中寻找a标签,需要在//前面加一个.,否则就会在整个html中寻找a标签