python爬虫xpath的用法
一、xpath介绍
XPath 是一门在 文档中查找信息的语言。XPath 用于在 文档中通过元素和属性进行导航。
XPath 使用路径表达式在 文档中进行导航
XPath 包含一个标准函数库
XPath 是 XSLT 中的主要元素
试验所使用的html代码
import l .html
test_data = \"\"\"
<div>
<ul>
<li class=\"item-0\"><a href=\" 1.html\" id=\"places_neighbours__row\">9,596,960first item</a></li>
<li class=\"item-1\"><a href=\" 2.html\">second item</a></li>
<li class=\"item-inactive\"><a href=\" 3.html\">third item</a></li>
<li class=\"item-1\"><a href=\" 4.html\" id=\"places_neighbours__row\">fourth item</a></li>
<li class=\"item-0\"><a href=\" 5.html\">fifth item</a></li>
<li class=\"good-0\"><a href=\" 5.html\">fifth item</a></li>
</ul>
<book>
< lang=\"aaengbb\">Harry Potter</ >
<price id=\"places_neighbours__row\">29.99</price>
</book>
<book>
< lang=\"zh\">Learning </ >
<price>39.95</price>
</book>
<book>
< >Python</ >
<price>40</price>
</book>
</div>
\"\"\"
\'\'\'
/ 从根标签开始
// 从当前标签
* 通配符
//div/book[1]/ 选择div下第一个book标签的 元素
//div/book/ [@lang= \"zh\"] 选择 属性含有lang且内容是zh的 元素
//div/book/ //book/ // 具有相同的结果,因为使用相对路径最终都指向
//book/ /@* 将 所有的属性值选择选择出来
//book/ /text() 将 的内容选择出来,使用内置text()函数
//a[@href=\' 1.html\'and @id=\'places_neighbours__row\']
//div/book[last()]/titlt/text() #将最后一个book元素选出来
//div/book[price > 39]/ /text() 将book子标签price数值大于39的选择出来
//li[starts-with(@class,\"item\")]/a/text() 将class属性前缀是item的li标签选出
// [contains(@lang,\"eng\")] 将 属性lang含有eng关键字的标签选出
\'\'\'
html = l .html.fromstring(test_data)
html_data = html.xpath(\'//div/book[1]/ \')
print(html_data)
# print(dir(html_data[0]))
for i in html_data:
print(i.text)
继续阅读与本文标签相同的文章
上一篇 :
宽带到期不用了,没注销,继续产生费用合理吗?
下一篇 :
NS2 trace旧格式
-
Mac高效开发之iTerm2、Prezto和Solarized主题
2026-05-18栏目: 教程
-
将阿里云产品整合成为高校课程实训的训练营产品的实践(四)
2026-05-18栏目: 教程
-
中间人攻击,HTTPS也可以被碾压
2026-05-18栏目: 教程
-
什么叫做IaC,与DevOps有什么关系?如何实现?
2026-05-18栏目: 教程
-
解读《运维知识体系》,直面自动化运维的“灵魂八问”
2026-05-18栏目: 教程
