繁体   English   中英

如果条件为真,则Scrapy获取href值的值

[英]Scrapy get the value of a href value if the condition is true

我已经用以下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 > a的href值中,该链接具有i tag

我可以做这个:

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

但是,如果我在第2页上,将无法使用。因此,如果a tag具有i tag的子元素,则最好获取a 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>

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

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

请注意,为避免误报,我们将concat用于class属性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/'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM