Python lxml/beautiful soup查找网页上的所有链接

2024-04-25 23:18:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本来读取网页,并建立一个符合特定条件的链接数据库。现在我被lxml困住了,并且理解了如何从html中获取所有的<a href>。。。

result = self._openurl(self.mainurl)
content = result.read()
html = lxml.html.fromstring(content)
print lxml.html.find_rel_links(html,'href')

Tags: self脚本数据库网页read链接htmlresult
3条回答

使用XPath。比如(不能从这里测试):

urls = html.xpath('//a/@href')

我想提供另一种基于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]

使用^{},lxml为这个任务提供了一个极好的功能。

This yields (element, attribute, link, pos) for every link [...] in an action, archive, background, cite, classid, codebase, data, href, longdesc, profile, src, usemap, dynsrc, or lowsrc attribute.

相关问题 更多 >