etree.HTML.xpath()后面应该接什么参数
时间: 2023-05-27 20:06:00 浏览: 97
etree.HTML.xpath()应该接XPath表达式作为参数,用于选择HTML文档中的元素。例如:
```python
from lxml import etree
html = """
<html>
<body>
<div class="container">
<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
</body>
</html>
"""
tree = etree.HTML(html)
# 选择所有的<p>元素
paragraphs = tree.xpath('//p')
print(paragraphs)
# 选择class属性为"container"的<div>元素下的所有<p>元素
container_paragraphs = tree.xpath('//div[@class="container"]/p')
print(container_paragraphs)
# 选择第一个<p>元素的文本内容
first_paragraph = tree.xpath('//p/text()')[0]
print(first_paragraph)
```
阅读全文