1. 程式人生 > >帶引數的scrapy專案爬蟲

帶引數的scrapy專案爬蟲

本章我們將會根據特定的 tag 來爬取 " http://quotes.toscrape.com/ ",的內容。

首先,我們先觀察這個網站的 url 結構,以 humor 這個 tag 為例,它的 url 是這樣的:" http://quotes.toscrape.com/tag/humor/ "。可見這個網站某個 tag 的 url 是:" http://quotes.toscrape.com/tag/ + tage_name "

下面我們來構建一個帶引數 tag 的爬蟲,tag 為我們選擇要爬取的 tag。

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

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        url = 'http://quotes.toscrape.com/tag/{}'.format(self.tag)
        yield scrapy.Request(url, self.parse)

    # 根據 tag 頁面爬取內容並處理翻頁
    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').extract_first(),
                'author': quote.css('small.author::text').extract_first(),
            }

        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, self.parse)

 


 

也可以使用 python 的內建函式 getattr()來實現。

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

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        url = 'http://quotes.toscrape.com/'
        # 如果 self.tag 存在返回 tag 本身的值,不存在返回 None
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + 'tag/' + tag
        # 把構建好的 url 用 parse() 方法處理
        yield scrapy.Request(url, self.parse)

    # 根據 tag 頁面爬取內容並處理翻頁
    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').extract_first(),
                'author': quote.css('small.author::text').extract_first(),
            }

        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, self.parse)

 


 

我們還能直接在 __init__,用超類的方法來定義 start_urls

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

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def __init__(self, tag=None, *args, **kwargs):
        super(QuotesSpider, self).__init__(*args, **kwargs)
        self.start_urls = ['http://quotes.toscrape.com/tag/{}'.format(tag)]

    # 根據 tag 頁面爬取內容並處理翻頁
    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').extract_first(),
                'author': quote.css('small.author::text').extract_first(),
            }

        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, self.parse)

 


 

在命令列使用爬蟲爬取時,我們用 -a 來傳遞引數:

scrapy crawl quotes -o quotes-humor.json -a tag=humor

現在,tag 為 humor 的所有資訊都被爬取並儲存為 json 檔案了。