我正在编写一个脚本来阅读网页,并构建符合特定条件的链接数据库。现在我坚持LXML并了解如何从HTML获取所有<a href>
的...Python lxml /美丽的汤,可以查找网页上的所有链接
result = self._openurl(self.mainurl)
content = result.read()
html = lxml.html.fromstring(content)
print lxml.html.find_rel_links(html,'href')
我正在编写一个脚本来阅读网页,并构建符合特定条件的链接数据库。现在我坚持LXML并了解如何从HTML获取所有<a href>
的...Python lxml /美丽的汤,可以查找网页上的所有链接
result = self._openurl(self.mainurl)
content = result.read()
html = lxml.html.fromstring(content)
print lxml.html.find_rel_links(html,'href')
使用XPath。喜欢的东西(不能从这里测试):
urls = html.xpath('//a/@href')
非常感谢你!我将测试 – Cmag 2011-05-25 21:29:46
'html.xpath(“//一个” )',然后(离开我的头顶)'.attr ['href']'为内容的url和'.text'。 – 2011-05-25 21:53:55
随着iterlinks
,LXML提供承担这一任务的优秀功能。
这会为动作,归档,背景,引用,classid,codebase,数据,href,longdesc,配置文件,src,usemap中的每个链接产生(element,attribute,link,pos) ,dynsrc或lowsrc属性。
我想提供一个基于lxml的替代解决方案。
该解决方案使用在lxml.cssselect提供的功能
import urllib
import lxml.html
from lxml.cssselect import CSSSelector
connection = urllib.urlopen('http://www.yourTargetURL/')
dom = lxml.html.fromstring(connection.read())
selAnchor = CSSSelector('a')
foundElements = selAnchor(dom)
print [e.get('href') for e in foundElements]
这已被要求数十次,并具有很好的答案,如:http://stackoverflow.com/questions/1080411/retrieve-links- from-web-page-using-python-and-beautiful-soup – 2011-05-25 21:29:17