2017-05-06 71 views
1

我已经被刮取的页面,这个网站的内容:Scrapy得到一个href的值的值,如果条件为真

<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的子元素,这将无法正常工作。我怎样才能做到这一点?

更新(第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> 

回答

2

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

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

请注意,以避免fal我们正在使用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/' 
+0

我很抱歉,但XPath表达式是行不通的。如果我在第二页上,它显示第一页。如果我在第3页(最后一页),则显示第2页。 – Robin

+0

@Robin可能是因为你在'a'里面有'i'元素的要求是无效的吗?我只是按照说明。你可以发布如何看HTML,如果你在第二页上? – alecxe

+0

即使是css版本也不行。如果我在第二页上,它会得到正确的网址。但是如果我在第三页(最后一页),它会回到第二页。 – Robin