.selectXpath()
时间: 2024-05-07 22:20:04 浏览: 5
`.selectXpath()` 是 Python 中 lxml 库中 Element 对象的方法,用于根据 XPath 表达式选取符合条件的子元素或属性。它的语法格式为:
```python
element.select(xpath, namespaces=None)
```
其中,`xpath` 是一个 XPath 表达式,`namespaces` 是一个命名空间字典,用于解析 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>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
```
我们可以使用以下代码选取所有 `<book>` 元素:
```python
from lxml import etree
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>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
"""
root = etree.fromstring(xml)
books = root.xpath("//book")
print(books)
```
这段代码打印出的结果是:
```
[<Element book at 0x7f9d9dcc5a40>, <Element book at 0x7f9d9dcc5b40>, <Element book at 0x7f9d9dcc5c80>]
```
其中,`books` 是一个包含所有选取的 `<book>` 元素的列表。