【问题标题】:Find all links within a div using lxml使用 lxml 查找 div 中的所有链接
【发布时间】:2013-05-04 19:28:46
【问题描述】:

我正在编写一个工具,该工具需要收集网页上 div 内的所有 url,但该 div 之外没有 url。简化后的页面看起来像这样:

<div id="bar">
   <a link I dont want>
   <div id="foo">
      <lots of html>
      <h1 class="baz">
         <a href=”link I want”>
      </h1>
      <h1 class="caz">
         <a href=“link I want”>
      </h1>
   </div>
</div>

当使用 Firebug 选择 div 并选择 XPath 时,我得到://*[@id="foo"]。到目前为止,一切都很好。但是,我一直在尝试查找 div foo 中的所有 url。请帮助我找到一种方法来提取由元素中的 href 定义的 url。

类似于我正在使用 w3schools 的示例代码:

import mechanize
import lxml.html
import cookielib

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'WatcherBot')]

r = br.open('http://w3schools.com/')
html = br.response().read()
root = lxml.html.fromstring(html)

hrefs = root.xpath('//*[@id="leftcolumn"]')

# Found no solution yet. Stuck

感谢您的宝贵时间!

【问题讨论】:

    标签: python web-crawler lxml python-2.x mechanize-python


    【解决方案1】:

    你可能想要这个:

    hrefs = root.xpath('//div[@id="foo"]//a/@href')
    

    这将为您提供来自a 标记中的所有href 值的列表,这些值位于任何级别的&lt;div id="foo"&gt;

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      相关资源
      最近更新 更多