python - 为 html 表提取 lxml xpath

标签 python html xpath html-table lxml

我有一个类似于以下的 html 文档:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
    <div id="Symbols" class="cb">
    <table class="quotes">
    <tr><th>Code</th><th>Name</th>
        <th style="text-align:right;">High</th>
        <th style="text-align:right;">Low</th>
    </tr>
    <tr class="ro" onclick="location.href='/xyz.com/A.htm';" style="color:red;">
        <td><a href="/xyz.com/A.htm" title="Display,A">A</a></td>
        <td>A Inc.</td>
        <td align="right">45.44</td>
        <td align="right">44.26</td>
    <tr class="re" onclick="location.href='/xyz.com/B.htm';" style="color:red;">
        <td><a href="/xyz.com/B.htm" title="Display,B">B</a></td>
        <td>B Inc.</td>
        <td align="right">18.29</td>
        <td align="right">17.92</td>
</div></html>

我需要从表中提取code/name/high/low信息。

我使用了 Stack Over Flow 中类似示例之一的以下代码:

#############################
import urllib2
from lxml import html, etree

webpg = urllib2.urlopen(http://www.eoddata.com/stocklist/NYSE/A.htm).read()
table = html.fromstring(webpg)

for row in table.xpath('//table[@class="quotes"]/tbody/tr'):
    for column in row.xpath('./th[position()>0]/text() | ./td[position()=1]/a/text() | ./td[position()>1]/text()'):
        print column.strip(),
    print

#############################

我没有得到任何输出。我必须将第一个循环 xpath 从 table.xpath('//table[@class="quotes"]/tbody/tr 更改为 table.xpath('//tr') ')

我只是不明白为什么 xpath('//table[@class="quotes"]/tbody/tr') 不起作用。

最佳答案

您可能正在查看 Firebug 中的 HTML,对吗?浏览器将插入隐式标签 <tbody>当它不存在于文档中时。 lxml 库将只处理原始 HTML 字符串中存在的标签。

在您的 XPath 中省略 tbody 级别。例如,这有效:

tree = lxml.html.fromstring(raw_html)
tree.xpath('//table[@class="quotes"]/tr')
[<Element tr at 1014206d0>, <Element tr at 101420738>, <Element tr at 1014207a0>]

关于python - 为 html 表提取 lxml xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5586296/

相关文章:

python - 如何使用 Selenium 和 Python 将文本发送到电子邮件字段

xpath - Xpath/xQuery的月份差异

python - 为什么 Python 3 shell 中的文本格式与生成的文本文件不同?

python - 尝试理解 Python Unicode 异常

python - 如何在Shapely中获取LineString的端点

html - 当媒体查询为 992px 及以上时,我无法让我的 html 程序中的部分继续在一行上

python - 为特定 JSON 格式生成 python 解析器

javascript - 使 onKeyDown 触发 HTML 按钮的 onClick 事件

php - 一个按钮工作,其他按钮出现错误 : "Notice: Undefined index: dbconfig.php on line 6"

javascript - 使用 XPath/XMLHttpRequest 解析 HTML