[英]How to extract links from a webpage using lxml, XPath and Python?
我有這個xpath查詢:
/html/body//tbody/tr[*]/td[*]/a[@title]/@href
它使用title屬性提取所有鏈接 - 並在FireFox的Xpath檢查程序附加組件中提供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="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']
Firefox在呈現時向html 添加了額外的html標記 ,使得firebug工具返回的xpath與服務器返回的實際html不一致(以及urllib / 2將返回的內容)。
刪除<tbody>
標簽通常可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.