正在 python 中使用 lxml 解析 html 页面

Parsing html page with lxml in python

我想在 python.

中用 lxml 解析这个 Xpath 查询
.//*[@id='content_top']/article/div/table/tbody/tr[5]/td/p/text()

我检查了 Firepath 中的 xpath 查询(xpath 的 firebug 扩展),它有效,但我的 python 代码没有显示任何内容。 这是来源。

from lxml import html
import requests

page = requests.get("http://www.scienzeetecnologie.uniparthenope.it/avvisi.html")
tree = html.fromstring(page.text)
avvisi = tree.xpath(".//*[@id='content_top']/article/div/table/tbody/tr[5]/td/p/text()")
print(avvisi)

输出是 "[]".

源 html 中没有实际的 <tbody> 元素,它只是 HTML 解析器添加的 DOM 中的一个元素。

firebug 实际上显示 DOM(我猜 firepath 是一个 firebug 扩展,适用于此 DOM(而不是源 html)).

有关 <tbody> 的更详细解释以及 firebug 显示它的原因,请查看 SO 问题的答案 - Why does firebug add <tbody> to <table>? or this question - Why do browsers insert tbody element into table elements?


在您的情况下,从 xpath 中删除 <tbody> 将使其工作,示例 -

avvisi = tree.xpath(".//*[@id='content_top']/article/div/table/tr[5]/td/p/text()")