【问题标题】:Scraperwiki scrape query: using lxml to extract linksScraperwiki 抓取查询:使用 lxml 提取链接
【发布时间】:2012-07-09 17:59:18
【问题描述】:

我怀疑这是一个微不足道的查询,但希望有人可以帮助我解决我在尝试构建的刮板中使用 lxml 得到的查询。

https://scraperwiki.com/scrapers/thisisscraper/

我正在逐行阅读教程 3,到目前为止,我一直在尝试提取下一页链接。我可以使用 cssselect 来识别链接,但我无法弄清楚如何仅隔离 href 属性而不是整个锚标记。

谁能帮忙?

def scrape_and_look_for_next_link(url):
    html = scraperwiki.scrape(url)
    print html
    root = lxml.html.fromstring(html) #turn the HTML into lxml object
    scrape_page(root)
    next_link = root.cssselect('ol.pagination li a')[-1]

    attribute = lxml.html.tostring(next_link)
    attribute = lxml.html.fromstring(attribute)

    #works up until this point
    attribute = attribute.xpath('/@href')
    attribute = lxml.etree.tostring(attribute)
    print attribute

【问题讨论】:

    标签: python-2.7 lxml scraper scraperwiki


    【解决方案1】:

    CSS 选择器可以选择 具有 href 属性的元素,例如。 a[href] 但他们不能自己提取属性值。

    从 cssselect 中获取元素后,您可以使用 next_link.get('href') 获取属性的值。

    【讨论】:

      【解决方案2】:
      link = link.attrib['href']
      

      应该有效

      【讨论】:

        猜你喜欢
        • 2014-06-01
        • 1970-01-01
        • 2019-06-05
        • 2013-04-28
        • 2016-01-23
        • 2018-02-22
        • 2019-08-24
        • 2016-04-20
        • 2018-11-03
        相关资源
        最近更新 更多