如何使用lxml,XPath和Python从网页中提取链接?

我有这个xpath查询:

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

它使用title属性提取所有链接 – 并在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文本(链接)?

最佳答案
我能够使用以下代码:

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="https://stackoverflow.com/foobar" title="Foobar">A link</a></td>
        </tr>
        <tr>
          <td><a href="https://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')

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

转载注明原文:如何使用lxml,XPath和Python从网页中提取链接? - 代码日志