5

我有这个 xpath 查询:

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

它提取所有带有 title 属性的链接 - 并hrefFireFox 的 Xpath 检查器插件中提供

但是,我似乎无法将它与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 下获取href包含属性标题的超链接的文本(链接) ?lxml

4

2 回答 2

12

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

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']
于 2010-01-18T09:03:58.280 回答
3

Firefox在渲染时会在 html 中添加额外的 html 标签,使得 firebug 工具返回的 xpath 与服务器返回的实际 html 不一致(以及 urllib/2 将返回的内容)。

删除<tbody>标签通常可以解决问题。

于 2011-12-06T01:48:51.877 回答