python xpath string
时间: 2023-07-09 18:46:49 浏览: 45
您好!针对您的问题,我理解您想要在 Python 中使用 XPath 解析字符串,是吗?
如果是这样,您可以使用 Python 中的 lxml 库来解析 XML 或 HTML,其中包含了 XPath 的相关功能。
下面是一个简单的例子,假设我们有如下的 XML 字符串:
```xml
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
```
我们可以使用 lxml 库的 etree 模块来解析该字符串,并使用 XPath 来获取其中的元素。
```python
from lxml import etree
xml_str = '''
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
'''
# 解析 XML 字符串
root = etree.fromstring(xml_str)
# 使用 XPath 获取元素
titles = root.xpath('//title')
for title in titles:
print(title.text)
```
输出结果为:
```
Everyday Italian
Harry Potter
```
在上述代码中,我们使用 `etree.fromstring()` 方法将 XML 字符串解析为一个 Element 对象,然后使用 `root.xpath()` 方法传入 XPath 表达式来获取元素。在这个例子中,我们使用了 `//title` 表达式来获取文档中所有的 `title` 元素。
希望这个例子能帮助到您!如果您有任何问题,可以随时向我提问。