XPath的使用:
bookStore.xml文档内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
<author>LuoLing</author>
</book>
<book>
<title lang="eng">Learing Python</title>
<price>39.95</price>
</book>
</bookstore>
1. 安装:lxml模块
2. 导入库:
from lxml import etree
3.使用:
xmls = etree.parse('bookStore.xml') result = xmls.xpath('/bookstore/book[price>35]/title') for t in result: print(t.text) books = xmls.xpath('/bookstore/book') if len(books) >= 2: print(books[-2]) titles = xmls.xpath('/bookstore/book/title') for t in titles: attr = t.xpath('attribute::*') if len(attr) > 0: print(t)学习网址:
http://www.w3school.com.cn/xpath/xpath_intro.asp