python-3.x - 从另一个 python 脚本运行一个scrapy程序
问题描述
这个问题以前已经回答过,但答案已经有好几年了。
在我的“项目”中,我有 4 个蜘蛛,每一个都处理我遇到的不同类型的产品(刮取亚马逊 ATM)。每个产品都有一个类别,例如,如果我想刮“笔记本电脑”,我使用一个刮板,但如果目标是刮衣服,我还有另一个。
那么,是否有一种方法可以运行 python 脚本,根据我必须抓取的产品(从 txt 文件中读取产品)调用不同的蜘蛛?
代码看起来像这样
#Imports
def scrapyProject():
#Get the products I want to scrape
if productIsClothes:
runClothesSpider
else productIsGeneric:
runGenericSpider
我知道前面的代码很粗糙,它是最终代码的草图。
它还有助于了解我需要哪些导入才能使程序正常工作
解决方案
您可以使用 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()
推荐阅读
- android - 非系统应用之间可以使用 sendOrderedBroadcast 吗?
- c - gdb - 打印宏名称而不是值
- java - JProgressBar 内的 Java swing 不透明 JProgressBar
- docker - TeamCity - docker-compose - 无法映射 URL
- html - 如何在自定义样式的 html 范围输入上具有透明背景?
- r - 使用前导值的操作填充 NA
- python - 我无法使用 Python 和 Facebook Marketing API 获取所有 Facebook 活动的统计信息
- git - 合并到特定分支后如何创建对 master 的合并请求
- javascript - 如何在 Wordpress 中将当前页面 URL 的一部分(最后五位数字)拉到页面内的 iFrame 中?
- python - 如何将集群用于多个图像?