[XPath] XPath 与 lxml (五)XPath 实例
2024-09-02 07:47:38
本文继续沿用第三章的 XML 示例文档。
选取价格高于30的 price 节点
# 从父节点进行筛选
>>> root.xpath('//book[price>30]/price')
[<Element price at 0x2d888c8>] # 直接对 price 进行筛选
>>> root.xpath('//price[text()>30]')
[<Element price at 0x2d888c8>]
选取 price 高于 30 的 title 节点
# 从父节点开始选取
>>> root.xpath('//book[price>30]/title')
[<Element title at 0x2d88878>] # 从节点本身选取
>>> root.xpath('//price[text()>30]//preceding-sibling::title|following-sibling::title')
[<Element title at 0x2d88878>] # 从 price 到父节点选取
>>> root.xpath('//price[text()>30]//parent::*/title')
[<Element title at 0x2d88878>]
处理命名空间
>>> xml = """<?xml version="1.0" encoding="utf8"?>
<bookstore xmlns:a="http://www.google.com">
<a:book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</a:book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>""" # 获取根节点
>>> root = etree.fromstring(xml) # 选取不带命名空间的 book 元素
>>> root.xpath('//book')
[<Element book at 0x2d88940>] # 选取所有的 book 元素,无论是否含有命名空间
# 其中 namespace 参数为一个字典对象,映射了命名空间前缀,本例中直接使用了文档原有的命名空间与前缀。
>>> root.xpath('//a:book|//book', namespaces=root.nsmap)
[<Element {http://www.google.com}book at 0x2d88878>, <Element book at 0x2d88940>]
最新文章
- 《爵迹》侵权链接多为个人用户分享到个人网盘 总结说明:推广途径为 网盘>;微博>;博客>;贴吧>;知道
- RecyclerView的基本创建
- 新建数据库,然后使用SQL语句创建表、存储过程、用户说明
- SQLite学习第03天:环境搭建
- Ajax请求安全性讨论 - Eric.Chen(转)
- NDK 的helloworld步奏
- Android应用开发实例篇(1)-----简易涂鸦板
- EF的四种开发模式
- 可以随鼠标拖拽的div
- 记MVC学习过程中一次传参到View时遇到的错误
- 《Office 365开发入门指南教程》正式上线,限时优惠和邀请分享推广
- java中线程安全的map是ConcurrentHashMap
- 使用Python编写简单的端口扫描器的实例分享【转】
- Ubuntu14.04 libboost_program_options.so.1.54.0: cannot open shared object file: No such file or directory
- 山寨";每日故宫";应用的图层遮罩效果
- soj1763.传球游戏
- Linux Shell管道调用用户定义函数(使shell支持map函数式特性)
- 匿名方法,lambad表达式,匿名类
- 【转载】使用SoapUI 测试Web Service
- P2341 [HAOI2006]受欢迎的牛(tarjan+缩点)
热门文章
- [Qt] 利用QtWebKit完成JavaScript访问C++对象
- Ubuntu中基于QT的系统网线连接状态的实时监视
- ssh 中 远程文件传输
- 在C++中调用DLL中的函数(2)
- 【Html】div 加载 html页面的方法
- 第三百六十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)基本的索引和文档CRUD操作、增、删、改、查
- ZBar与ZXing使用后感觉
- e808. 建立菜单栏,菜单,菜单项
- 理解并实现PubSub模式
- Python——hmac