Python XPath 不断返回空列表

Python XPath keeps returning empty list

Python 中通过 lxml 的 XPath 让我 运行 转了一圈。我无法让它从 HTML table 中提取文本,尽管我认为它是正确的 XPath。我正在使用 Chrome 检查和提取 XPath,然后在我的代码中使用它。

这里是 HTML table 直接取自页面:

<div id="vehicle-detail-model-specs-container">
<table id="vehicle-detail-model-specs" class="table table-striped vdp-feature-table">
    <!-- Price -->
    <tr>
                <td><strong>Price:</strong></td>
                    <td>
                            <strong id="vehicle-detail-price" itemprop="price">$ 2,210.00</strong>            </td>
            </tr>
                    <!-- VIN -->
    <tr><td><strong>VIN</strong></td><td>&nbsp;*0343</td></tr>

    <!-- MILEAGE -->
    <tr><td><strong>Mileage</strong></td><td>0&nbsp;mi</td></tr>
</table>

我正在尝试提取里程。我使用的 XPath 是:

//*[@id="vehicle-detail-model-specs"]/tbody/tr[3]/td[2]

我使用的 Python 代码是:

page = requests.get(URL)
tree = html.fromstring(page.content)

mileage = tree.xpath('//*[@id="vehicle-detail-model-specs"]/tbody/tr[3]/td[2]')
print mileage

注意:我已经尝试将 /text() 添加到末尾,但我仍然一无所获,只是一个空列表 [].

我做错了什么,为什么我无法从上述示例中提取 table 值?

正如 Amber 指出的那样,您应该省略 tbody 部分。 当您的 table.

的 html 代码中没有 <tbody> 标记时,您在 xpath 中使用 tbody

使用您发布的 html,我可以使用以下 xpath 提取里程值:

tree.xpath('//*[@id="vehicle-detail-model-specs"]/tr[3]/td[2]')[0].text_content()