如何在程序中向scrapy爬虫传递参数?

2024-03-11

我是 python 和 scrapy 的新手。我用的是这个博客的方法以编程方式运行多个 scrapy 蜘蛛 http://kirankoduru.github.io/python/multiple-scrapy-spiders.html在烧瓶应用程序中运行我的蜘蛛。这是代码:

# list of crawlers
TO_CRAWL = [DmozSpider, EPGDspider, GDSpider]

# crawlers that are running 
RUNNING_CRAWLERS = []

def spider_closing(spider):
    """
    Activates on spider closed signal
    """
    log.msg("Spider closed: %s" % spider, level=log.INFO)
    RUNNING_CRAWLERS.remove(spider)
    if not RUNNING_CRAWLERS:
        reactor.stop()

# start logger
log.start(loglevel=log.DEBUG)

# set up the crawler and start to crawl one spider at a time
for spider in TO_CRAWL:
    settings = Settings()

    # crawl responsibly
    settings.set("USER_AGENT", "Kiran Koduru (+http://kirankoduru.github.io)")
    crawler = Crawler(settings)
    crawler_obj = spider()
    RUNNING_CRAWLERS.append(crawler_obj)

    # stop reactor when spider closes
    crawler.signals.connect(spider_closing, signal=signals.spider_closed)
    crawler.configure()
    crawler.crawl(crawler_obj)
    crawler.start()

# blocks process; so always keep as the last statement
reactor.run()

这是我的蜘蛛代码:

class EPGDspider(scrapy.Spider):
name = "EPGD"
allowed_domains = ["epgd.biosino.org"]
term = "man"
start_urls = ["http://epgd.biosino.org/EPGD/search/textsearch.jsp?textquery="+term+"&submit=Feeling+Lucky"]
MONGODB_DB = name + "_" + term
MONGODB_COLLECTION = name + "_" + term

def parse(self, response):
    sel = Selector(response)
    sites = sel.xpath('//tr[@class="odd"]|//tr[@class="even"]')
    url_list = []
    base_url = "http://epgd.biosino.org/EPGD"

    for site in sites:
        item = EPGD()
        item['genID'] = map(unicode.strip, site.xpath('td[1]/a/text()').extract())
        item['genID_url'] = base_url+map(unicode.strip, site.xpath('td[1]/a/@href').extract())[0][2:]
        item['taxID'] = map(unicode.strip, site.xpath('td[2]/a/text()').extract())
        item['taxID_url'] = map(unicode.strip, site.xpath('td[2]/a/@href').extract())
        item['familyID'] = map(unicode.strip, site.xpath('td[3]/a/text()').extract())
        item['familyID_url'] = base_url+map(unicode.strip, site.xpath('td[3]/a/@href').extract())[0][2:]
        item['chromosome'] = map(unicode.strip, site.xpath('td[4]/text()').extract())
        item['symbol'] = map(unicode.strip, site.xpath('td[5]/text()').extract())
        item['description'] = map(unicode.strip, site.xpath('td[6]/text()').extract())
        yield item

    sel_tmp = Selector(response)
    link = sel_tmp.xpath('//span[@id="quickPage"]')

    for site in link:
        url_list.append(site.xpath('a/@href').extract())

    for i in range(len(url_list[0])):
        if cmp(url_list[0][i], "#") == 0:
            if i+1 < len(url_list[0]):
                print url_list[0][i+1]
                actual_url = "http://epgd.biosino.org/EPGD/search/"+ url_list[0][i+1]
                yield Request(actual_url, callback=self.parse)
                break
            else:
                print "The index is out of range!"

可以看到,有一个参数term = 'man'在我的代码中,它是我的一部分start urls。我不希望这个参数被固定,所以我想知道如何给出start url或参数term动态地在我的程序中?就像在命令行中运行蜘蛛一样,有一种方法可以传递参数,如下所示:

class MySpider(BaseSpider):

    name = 'my_spider'    

    def __init__(self, *args, **kwargs): 
      super(MySpider, self).__init__(*args, **kwargs) 

      self.start_urls = [kwargs.get('start_url')] 
And start it like: scrapy crawl my_spider -a start_url="http://some_url"

谁能告诉我如何处理这个问题?


首先,要在一个脚本中运行多个蜘蛛,推荐的方法是使用scrapy.crawler.CrawlerProcess http://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess, 你在哪里通过蜘蛛课程 http://doc.scrapy.org/en/latest/topics/practices.html?#run-scrapy-from-a-script而不是蜘蛛实例。

将参数传递给你的蜘蛛CrawlerProcess,您只需将参数添加到.crawl()在蜘蛛子类之后调用, 例如

    process.crawl(DmozSpider, term='someterm', someotherterm='anotherterm')

以这种方式传递的参数可用作蜘蛛属性(与-a term=someterm在命令行上)

最后,而不是构建start_urls in __init__,你可以达到同样的效果start_requests http://doc.scrapy.org/en/latest/topics/spiders.html?highlight=start_requests#scrapy.spiders.Spider.start_requests,你可以像这样构建初始请求,使用self.term:

def start_requests(self):
    yield Request("http://epgd.biosino.org/"
                  "EPGD/search/textsearch.jsp?"
                  "textquery={}"
                  "&submit=Feeling+Lucky".format(self.term))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在程序中向scrapy爬虫传递参数? 的相关文章

随机推荐

  • 如果总是与同一事物进行比较,是否有办法缩短条件?

    当我需要编写一个反复比较同一项目的条件时 我总是觉得很烦人 因为我会多次输入该项目 string x textBox1 Text if x apple x orange x banana 我想要这样的东西 但这当然不是正确的语法 if x
  • solveJsonModule 无法与 Angular 10 一起运行?

    我的全新 Angular 10 项目的资产文件夹中有一个基本的 JSON 文件 角度 CLI 10 0 1 节点 14 5 0 操作系统 win32 x64 TSC 版本 3 9 5 在我的 tsconfig json 中我有 compil
  • 从 Nib 或 Storyboard 设置 WKWebView 上的 WKWebViewConfiguration

    在 iOS 11 中 Apple 添加了在笔尖和情节提要上添加 WKWebViews 出口的功能集 使用自动设置的默认 WKWebViewConfiguration 时 它似乎工作正常 但是 我希望能够使用自定义 WKWebViewConf
  • 如何从高图表中删除“值”和“系列”?

    I m using highcharts on my website which looks great but I now want to remove these two labels from the chart 我尝试禁用各种标签
  • 如何获取google地图上的平均交通数据

    我想像这样在谷歌地图上显示平均流量层 但是 这张地图显示的是实时流量数据 而不是我想在谷歌地图上显示一段时间内的平均流量 这可能吗 或者任何其他地图 API 可以提供帮助吗 请为该问题加注星标问题跟踪器链接 https issuetrack
  • 如何在com.google.android.material.chip.Chip上设置chipText?

    我正在调查以下提供的材料成分 implementation group com google android material name material version 1 0 0 alpha3 namely com google and
  • PHP 彗星 usleep 阻塞 apache mpm?

    我那里有一颗彗星我以这种方式运行 while 循环 items statement gt fetchAll statement is a PDO Statement iteration 0 while count items 0 itera
  • 使用复制的 git 存储库安全吗?

    如果我使用以下命令复制跟踪文件夹rsync a or cp R 然后我可以像使用 git 克隆一样使用该副本吗 或者这会导致各种奇怪的问题吗 这一切都在我的计算机上运行 因此没有其他人访问该存储库 显然 git cloned 目录知道它是从
  • 动态计算 Pandas 中公式的表达式

    我想使用一个或多个数据帧列执行算术pd eval 具体来说 我想移植以下计算公式的代码 x 5 df2 D df1 A df1 B x 使用代码pd eval 使用理由pd eval是我想自动化许多工作流程 因此动态创建它们对我很有用 我的
  • 在 Linux 上以汇编形式输出整数

    这需要在纯汇编中完成 即没有库或对 C 的调用 我理解问题的本质 需要将整数除以 10 将一位数余数转换为 ASCII 输出 然后用商重复该过程 但由于某种原因 它不起作用 我在 x86 上使用 NASM 这是我到目前为止所拥有的 不输出任
  • UICollectionView 的单元格消失

    发生了什么 目前我有一个应用程序使用两个UICollectionViews里面一个UITableView 通过这种方式 我创建了一个看起来像 Pulse News 的应用程序 我的问题是 有时第 6 行和第 11 行完全消失 在本应是单元格
  • 我想通过 graph api 分享朋友的帖子

    我想通过 graph api 在 facebook 上分享一些帖子 但是没有这样的api 只有 饲料 存在 我尝试使用 me feed 图形 API 操作来分享我朋友的帖子 以及页面中的帖子 但它和我在 Facebook 网站上分享的不一样
  • 开发 BlackBerry OS6 需要哪个版本的 Blackberry JRE

    我下载了适用于 BlackBerry 的 Eclipse 插件 默认情况下具有 BlackBerry OS 7 运行时 我需要定位 BlackBerry OS 6 和 OS 7 设备 这也适用于 BlackBerry OS 6 还是我需要更
  • 加快我的批处理文件解析速度

    我有一个批处理文件 它从一个 txt 文件中获取输入 如下所示 Microsoft R Windows Script Host Version 5 8 Copyright C Microsoft Corporation All rights
  • System.String[] Split(Char[])' 方法无法识别

    我有以下数据 我想使用 Linq to Entities 过滤数据 但我收到异常 LINQ to Entities 无法识别方法 System String Split Char 方法 并且该方法不能翻译为 存储表达式 我的表中有以下数据
  • 为因子的每个级别附加一行总和

    我想为每个 Reg 添加一行总和 如下所示 Reg Res Pop 1 Total 1000915 2 A Urban 500414 3 A Rural 500501 4 Total 999938 5 B Urban 499922 6 B
  • UIPageViewController 在旋转时重置为第一页

    当用户旋转设备时 UIPageViewController从它显示的任何页面淡出回到第一页 这确实很烦人 尤其是当用户进入文档的多个页面时 它仅出现在 iOS 6 中 当用户旋转设备时 spineLocationForInterfaceOr
  • 如何分析Delphi应用程序中过多的内存消耗(PageFileUsage)?

    这是这个问题的后续 如何解释 FastMM 或 GetProcessMemoryInfo 报告的内存使用情况的差异 https stackoverflow com q 9704786 184404 我的 Delphi XE 应用程序使用大量
  • Visual Studio 大型解决方案

    我已经为我的 Web 应用程序提供了一个解决方案 其中包含近 12 个项目和 3 个网站 有一些项目用于多个网站 例如 MyProject BE MyProject BLL MyProject DAL MyProject Controls
  • 如何在程序中向scrapy爬虫传递参数?

    我是 python 和 scrapy 的新手 我用的是这个博客的方法以编程方式运行多个 scrapy 蜘蛛 http kirankoduru github io python multiple scrapy spiders html在烧瓶应