【问题标题】:Scrapy get the value of a href value if the condition is true如果条件为真,Scrapy 获取一个 href 值的值
【发布时间】:2017-10-05 00:07:35
【问题描述】:

我已经用这个 html 内容抓取了一个页面:

<div class="td-ss-main-content">
  <div class="td-page-header">...</div>
  <div class="td_module_16 td_module_wrap td-animation-stack">...</div>
  <div class="td_module_16 td_module_wrap td-animation-stack td_module_no_thumb">...</div>
  <div class="page-nav td-pb-padding-side">
    <span class="current">1</span>
    <a href="http://www.arunachaltimes.in/2017/05/06/page/2/" class="page" title="2">2</a>
    <a href="http://www.arunachaltimes.in/2017/05/06/page/3/" class="page" title="3">3</a>
    <a href="http://www.arunachaltimes.in/2017/05/06/page/2/"><i class="td-icon-menu-right"></i></a>
    <span class="pages">Page 1 of 3</span>
  </div>
</div>

现在我想获取下一页链接,如果它存在于.page-nav &gt; a 的a href 值中,它有一个i tag

我可以这样做:

response.css("div.page-nav > a")[2].css("::attr(href)").extract_first()

但是,如果我在第 2 页,这将不起作用。因此,如果 a tag 具有 i tag 的子元素,则最好获取它的值。我怎样才能做到这一点?

更新(第 2 页)

<div class="page-nav td-pb-padding-side">
    <a href="http://www.arunachaltimes.in/2017/05/06/"><i class="td-icon-menu-left"></i></a>
    <a href="http://www.arunachaltimes.in/2017/05/06/" class="page" title="1">1</a>
    <span class="current">2</span>
    <a href="http://www.arunachaltimes.in/2017/05/06/page/3/" class="page" title="3">3</a>
    <a href="http://www.arunachaltimes.in/2017/05/06/page/3/"><i class="td-icon-menu-right"></i></a>
    <span class="pages">Page 2 of 3</span>
</div>

更新(第 3 页最后一页)

<div class="page-nav td-pb-padding-side">
    <a href="http://www.arunachaltimes.in/2017/05/06/page/2/"><i class="td-icon-menu-left"></i></a>
    <a href="http://www.arunachaltimes.in/2017/05/06/" class="page" title="1">1</a>
    <a href="http://www.arunachaltimes.in/2017/05/06/page/2/" class="page" title="2">2</a>
    <span class="current">3</span>
    <span class="pages">Page 3 of 3</span>
</div>

【问题讨论】:

    标签: python html css scrapy


    【解决方案1】:

    您可以使用 XPath 表达式来实现它:

    //div[contains(concat(' ', @class, ' '), ' page-nav ')]/a[contains(concat(' ', i/@class, ' '), ' td-icon-menu-right ')]/@href
    

    请注意,为避免误报,我们使用concat for the class attribute check

    演示:

    $ scrapy shell file:////$PWD/index.html
    In [1]: response.xpath("//div[contains(concat(' ', @class, ' '), ' page-nav ')]/a[contains(concat(' ', i/@class, ' '), ' td-icon-menu-right ')]/@href").extract_first()
    Out[1]: u'http://www.arunachaltimes.in/2017/05/06/page/2/'
    

    【讨论】:

    • 很抱歉,Xpath 表达式不起作用。如果我在第二页,它显示第一页。如果我在第三页(最后一页),它会显示第二页。
    • @Robin 您是否要求在i 中包含i 元素无效?我只是按照说明进行操作。如果您在第二页,您能否发布 HTML 的外观?
    • 即使是 css 版本也不行。如果我在第二页,它会得到正确的 url。但如果我在第三页(最后一页),它会返回第二页。
    • @Robin 好吧,那不仅仅是i - 它是itd-icon-menu-right 类。请检查更新的答案。
    • 是的,我很粗心。谢谢。
    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多