创建请求的捷径

作为创建请求的捷径,你可以使用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支持网页直接跳转,不需要urljoin方法。需要注意的是response.follow只返回请求实例;你还是要生成这个请求的。

你也可以向选择器传递一个response.follow而不是字符串;此选择器应该可提取重要的属性:

    >>>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返回的是具有选择器所有结果的一个类似列表的对象,并非单一的选择器。像例子中的一个for循环,也可使用*response.follow(response.css('li.next a')[0])。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容