【问题标题】:How to extract links from a webpage using lxml, XPath and Python?如何使用 lxml、XPath 和 Python 从网页中提取链接?
【发布时间】:2011-01-06 06:43:45
【问题描述】:

我有这个 xpath 查询:

/html/body//tbody/tr[*]/td[*]/a[@title]/@href

它提取所有带有标题属性的链接 - 并在FireFox's Xpath checker add-on 中给出href

但是,我似乎无法将它与 lxml 一起使用。

from lxml import etree
parsedPage = etree.HTML(page) # Create parse tree from valid page.

# Xpath query
hyperlinks = parsedPage.xpath("/html/body//tbody/tr[*]/td[*]/a[@title]/@href") 
for x in hyperlinks:
    print x # Print links in <a> tags, containing the title attribute

这不会产生来自lxml 的结果(空列表)。

如何在 Python 下获取包含lxml 属性标题的超链接的href 文本(链接)?

【问题讨论】:

  • 您正在解析的文档是否设置了命名空间(xmlns)?

标签: python screen-scraping hyperlink lxml extraction


【解决方案1】:

我能够使用以下代码使其工作:

from lxml import html, etree
from StringIO import StringIO

html_string = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
<head/>
<body>
    <table border="1">
      <tbody>
        <tr>
          <td><a href="http://stackoverflow.com/foobar" title="Foobar">A link</a></td>
        </tr>
        <tr>
          <td><a href="http://stackoverflow.com/baz" title="Baz">Another link</a></td>
        </tr>
      </tbody>
    </table>
</body>
</html>'''

tree = etree.parse(StringIO(html_string))
print tree.xpath('/html/body//tbody/tr/td/a[@title]/@href')

>>> ['http://stackoverflow.com/foobar', 'http://stackoverflow.com/baz']

【讨论】:

    【解决方案2】:

    Firefox adds additional html tags 渲染时到 html,使得 firebug 工具返回的 xpath 与服务器返回的实际 html 不一致(以及 urllib/2 将返回的内容)。

    删除&lt;tbody&gt; 标签通常可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      相关资源
      最近更新 更多