簡體   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