今天就跟大家聊聊有关Scrapy中如何实现向Spider传入参数,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
在使用Scrapy爬取数据时,有时会碰到需要根据传递给Spider的参数来决定爬取哪些Url或者爬取哪些页的情况。
例如,百度贴吧的放置奇兵吧的地址如下,其中 kw参数用来指定贴吧名称、pn参数用来对帖子进行翻页。
/tupian/20230522/f 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 = ['/tupian/20230522/f % (tiebaName,pn)]
def parse(self, response):
print(response.request.url) # 结果:/tupian/20230522/f
新闻名称:Scrapy中如何实现向Spider传入参数-创新互联
标题网址:http://chengdu.cdxwcx.cn/article/degopj.html