如何通过xpath解析lxml中的子元素

use*_*108 0 python xpath lxml

page = urlopen(req)
doc = parse(page).getroot()
table = doc.xpath('/html/body/div/div/div/table')
table
<Element table ...>
doc.xpath('/html/body/div/div/div/table/tr')
<Element tr ...>...
table.xpath('/tr')
[]
Run Code Online (Sandbox Code Playgroud)

为什么不table.xpath('/tr')产生相同的元素列表doc.xpath('/html/body/div/div/div/table/tr')呢?

str*_*nac 5

这是因为以x开头的xpath /总是在文档根目录开始匹配。

为了避免这种情况,请省略斜线,或者将其显式并用于.匹配当前元素。
这些都应该起作用:

table.xpath('tr')
# or
table.xpath('./tr')
Run Code Online (Sandbox Code Playgroud)