更多爬虫例子

下面这个例子将会演示如何从 " http://quotes.toscrape.com/ " 中获取页面上所有作者(author)的页面链接,并爬取作者页面的相应信息,然后进入下一页重复上诉步骤,直到把网站所有作者信息都爬取完成。

# -*- coding: utf-8 -*-

import scrapy

class AuthorSpider(scrapy.Spider):
    name = 'author'
    start_urls = ['http://quotes.toscrape.com/']

    def parse(self, response):
        # 获取页面上所有作者的连接
        for href in response.css('.author + a::attr(href)').extract():
            # 获取到作者连接后,调用 parse_author 方法来爬取
            yield scrapy.Request(response.urljoin(href), 
                callback=self.parse_author)

        # 获取下一页连接并处理
        next_page = response.css('li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

    # 爬取作者页面,并提取相应的数据
    def parse_author(self, response):
        def extract_with_css(query):
            return response.css(query).extract_first().strip()

        yield {
            'name': extract_with_css('h3.author-title::text'),
            'birthdate': extract_with_css('.author-born-date::text'),
            'bio': extract_with_css('.author-description::text'),
        }

照样,我们用以下命令爬取:

scrapy crawl author -o items.json

值得注意的是,即使一个作者的链接出现多次,也不会被重复爬取,因为 Scrapy 默认情况下会自动过滤重复的 url;相关的设定可以通过 settings.py 中的 DUPEFILTER_CLASS 属性来调节。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容