首页 > 解决方案 > 从另一个 python 脚本运行一个scrapy程序

问题描述

这个问题以前已经回答过,但答案已经有好几年了。

在我的“项目”中,我有 4 个蜘蛛,每一个都处理我遇到的不同类型的产品(刮取亚马逊 ATM)。每个产品都有一个类别,例如,如果我想刮“笔记本电脑”,我使用一个刮板,但如果目标是刮衣服,我还有另一个。

那么,是否有一种方法可以运行 python 脚本,根据我必须抓取的产品(从 txt 文件中读取产品)调用不同的蜘蛛?

代码看起来像这样

#Imports

def scrapyProject():

    #Get the products I want to scrape
    if productIsClothes:

        runClothesSpider

    else productIsGeneric:

        runGenericSpider

我知道前面的代码很粗糙,它是最终代码的草图。

它还有助于了解我需要哪些导入才能使程序正常工作

标签: python-3.xweb-scrapingscrapy

解决方案


您可以使用 if 语句设置蜘蛛类:

import sys

import scrapy
from scrapy.crawler import CrawlerProcess

from project.spiders import Spider1, Spider2

def main():
    process = CrawlerProcess({})

    if sys.argv[1] == '1':
        spider_cls = Spider1
    elif sys.argv[1] == '2':
        spider_cls = Spider2
    else:
        print('1st argument must be either 1 or 2')
        return
    process.crawl(spider_cls)
    process.start() # the script will block here until the crawling is finished

if __name__ == '__main__':
    main()

推荐阅读