【发布时间】:2012-03-19 02:44:13
【问题描述】:
在浏览了用于 python 的 lxml 教程中的 xpath 之后,我发现很难理解 2 种对我来说似乎是错误的行为。首先,即使我的 xpath 表达式清楚地只选择了一个元素,lxml 似乎也会返回一个列表,其次,.xpath 似乎返回元素的父元素,而不是直接通过 xpath 搜索表达式选择的元素本身。
是我对 XPath 的理解全错了还是 lxml 确实有 bug?
复制我正在谈论的行为的脚本:
from lxml.html.soupparser import fromstring
doc = fromstring("""
<html>
<head></head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</body>
</html>
""")
print doc.xpath("//html")
#[<Element html at 1f385e0>]
#(This makes sense - return a list of all possible matches for html)
print doc.xpath("//html[1]")
#[<Element html at 1f385e0>]
#(This doesn't make sense - why do I get a list when there
#can clearly only be 1 element returned?)
print doc.xpath("body")
#[<Element body at 1d003e8>]
#(This doesn't make sense - according to
#http://www.w3schools.com/xpath/xpath_syntax.asp if I use a tag name
#without any leading / I should get the *child* nodes of the named
#node, which in this case would mean I get a list of
#p tags [<Element p at ...>, <Element p at ...>]
【问题讨论】: