今天就跟大家聊聊有關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 命令的源代碼,重新自定義一個專用命令。
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, args, 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, args, 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傳入參數有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。