gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:30:44 26 4
gpt4 key购买 nike

我有这个 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 抓取包含属性 title 的超链接的 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="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']

关于python - 如何使用 lxml、XPath 和 Python 从网页中提取链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2084670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com