創(chuàng)建請求的捷徑

作為創(chuàng)建請求的捷徑,你可以使用response.follow

    import scrapy

    class QuotesSpider(scrapy.Spider):
        name = "quotes"
        start_urls = [
            'http://quotes.toscrape.com/page/1/',
        ]
        def parse(self,response):
            for quote in response.css('div.quote'):
                yield{
                    'text':quote.css('span.text::text').extract_first(),
                    'author':quote.css('span small::text').extract_first(),
                    'tags':quote.css('div.tags a.tag::text').extract(),
                }
            next_page = response.css('li.next a::attr(href)').extract_first()
            if next_page is not None:
               yield response.follow(next_page,callback = self.parse)

scrapy.Request不同,response.follow支持網(wǎng)頁直接跳轉(zhuǎn),不需要urljoin方法。需要注意的是response.follow只返回請求實例;你還是要生成這個請求的。

你也可以向選擇器傳遞一個response.follow而不是字符串;此選擇器應(yīng)該可提取重要的屬性:

    >>>for href in response.css('li.next a::attr(href)'):
           yield response.follow(href, callback = self.parse)

對于<a>標簽元素,這里有個簡單方法:response.follow自動使用了它們的href屬性。所以代碼更簡潔:

    >>>for a in response.css('li.next a'):
           yield response.follow(a,callback = self.parse)

注意:resposne.follow(response.css('li.next a'))是無效值,因為response.css返回的是具有選擇器所有結(jié)果的一個類似列表的對象,并非單一的選擇器。像例子中的一個for循環(huán),也可使用*response.follow(response.css('li.next a')[0])。


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容