1. 程式人生 > 程式設計 >Scrapy中如何向Spider傳入引數的方法實現

Scrapy中如何向Spider傳入引數的方法實現

在使用Scrapy爬取資料時,有時會碰到需要根據傳遞給Spider的引數來決定爬取哪些Url或者爬取哪些頁的情況。

例如,百度貼吧的放置奇兵吧的地址如下,其中 kw引數用來指定貼吧名稱、pn引數用來對帖子進行翻頁。

https://tieba.baidu.com/f?kw=放置奇兵&ie=utf-8&pn=250

如果我們希望通過引數傳遞的方式將貼吧名稱和頁數等引數傳給Spider,來控制我們要爬取哪一個貼吧、爬取哪些頁。遇到這種情況,有以下兩種方法向Spider傳遞引數。

方式一

通過 scrapy crawl 命令的 -a 引數向 spider 傳遞引數。

# -*- coding: utf-8 -*-
import scrapy

class TiebaSpider(scrapy.Spider):
  name = 'tieba' # 貼吧爬蟲
  allowed_domains = ['tieba.baidu.com'] # 允許爬取的範圍
  start_urls = [] # 爬蟲起始地址

  # 命令格式: scrapy crawl tieba -a tiebaName=放置奇兵 -a pn=250
  def __init__(self,tiebaName=None,pn=None,*args,**kwargs):
    print('< 貼吧名稱 >: ' + tiebaName)
    super(eval(self.__class__.__name__),self).__init__(*args,**kwargs)
    self.start_urls = ['https://tieba.baidu.com/f?kw=%s&ie=utf-8&pn=%s' % (tiebaName,pn)]

  def parse(self,response):
    print(response.request.url) # 結果:https://tieba.baidu.com/f?kw=%E6%94%BE%E7%BD%AE%E5%A5%87%E5%85%B5&ie=utf-8&pn=250

方式二

仿照 scrapy 的 crawl 命令的原始碼,重新自定義一個專用命令。

Scrapy中如何向Spider傳入引數的方法實現

settings.py

首先,需要在settings.py檔案中增加如下配置來指定自定義 scrapy 命令的存放目錄。

# 指定 Scrapy 命令存放目錄
COMMANDS_MODULE = 'baidu_tieba.commands'

run.py

在指定的命令存放目錄中建立命令檔案,在這裡我們建立的命令檔案為 run.py ,將來執行的命令格式為:
scrapy run [ -option option_value]

import scrapy.commands.crawl as crawl
from scrapy.exceptions import UsageError
from scrapy.commands import ScrapyCommand


class Command(crawl.Command):

  def add_options(self,parser):
    # 為命令新增選項
    ScrapyCommand.add_options(self,parser)
    parser.add_option("-k","--keyword",type="str",dest="keyword",default="",help="set the tieba's name you want to crawl")
    parser.add_option("-p","--pageNum",type="int",action="store",dest="pageNum",default=0,help="set the page number you want to crawl")

  def process_options(self,args,opts):
    # 處理從命令列中傳入的選項引數
    ScrapyCommand.process_options(self,opts)
    if opts.keyword:
      tiebaName = opts.keyword.strip()
      if tiebaName != '':
        self.settings.set('TIEBA_NAME',tiebaName,priority='cmdline')
    else:
      raise UsageError("U must specify the tieba's name to crawl,use -kw TIEBA_NAME!")
    self.settings.set('PAGE_NUM',opts.pageNum,priority='cmdline')

  def run(self,opts):
    # 啟動爬蟲
    self.crawler_process.crawl('tieba')
    self.crawler_process.start()

pipelines.py

在BaiduTiebaPipeline的open_spider()方法中利用 run 命令傳入的引數對TiebaSpider進行初始化,在這裡示例設定了一下start_urls。

# -*- coding: utf-8 -*-
import json

class BaiduTiebaPipeline(object):

  @classmethod
  def from_settings(cls,settings):
    return cls(settings)

  def __init__(self,settings):
    self.settings = settings

  def open_spider(self,spider):
    # 開啟爬蟲
    spider.start_urls = [
      'https://tieba.baidu.com/f?kw=%s&ie=utf-8&pn=%s' % (self.settings['TIEBA_NAME'],self.settings['PAGE_NUM'])]

  def close_spider(self,spider):
    # 關閉爬蟲
    pass

  def process_item(self,item,spider):
    # 將帖子內容儲存到檔案
    with open('tieba.txt','a',encoding='utf-8') as f:
      json.dump(dict(item),f,ensure_ascii=False,indent=2)
    return item

設定完成後,別忘了在settings.py中啟用BaiduTiebaPipeline。

ITEM_PIPELINES = {
  'baidu_tieba.pipelines.BaiduTiebaPipeline': 50,}

啟動示例

大功告成,參照如下命令格式啟動貼吧爬蟲。

scrapy run -k 放置奇兵 -p 250

Scrapy中如何向Spider傳入引數的方法實現

參考文章:

https://blog.csdn.net/c0411034/article/details/81750028

https://blog.csdn.net/qq_24760381/article/details/80361400

https://blog.csdn.net/qq_38282706/article/details/80991196

到此這篇關於Scrapy中如何向Spider傳入引數的方法實現的文章就介紹到這了,更多相關Scrapy Spider傳入引數內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!