问题描述
我有一个任务,必须使用Scrapy抓取一些网站。我还必须使用Django删除和编辑一些URL。我想使用Django 3.1和Scrapy 2.3.0。
我已经尝试使用Django-dynamic-scraper和Djangoitem。由于某些版本问题,我无法使用它们。
有一个执行Django命令的类,称为call_command
call_command('Scrapy crawl ../first_bot/first_bot/spider.py',stdout=out)
但这仅用于Django命令。
当我在Django上单击一个按钮时,有什么方法可以执行scrapy模块?
解决方法
在python文件start.py中粘贴代码,并在scrapy目录中使用此代码。
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
process = CrawlerProcess(get_project_settings())
# var = name of spider
process.crawl(var)
process.start()
在django中,您可以根据需要在此处使用以下代码运行start.py
import platform
import os
if plt == "Windows":
cwd = os.path.join("<path to file>","start.py")
os.system('{} {}'.format('python',cwd))
elif plt == "Linux":
cwd = os.path.join("<path to file>","start.py")
os.system('{} {}'.format('python3',cwd))