如何在 Django 中执行 Scrapy?

我有一个任务,我必须用 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 模块?


智慧大石
浏览 80回答 1
1回答

斯蒂芬大帝

将代码粘贴到 python 文件 start.py 中,并在 scrapy 目录中使用此代码。from scrapy.crawler import CrawlerProcessfrom scrapy.utils.project import get_project_settingsprocess = CrawlerProcess(get_project_settings())# var = name of spiderprocess.crawl(var)process.start()在 django 中运行 start.py 在这里使用你喜欢的代码import platformimport osif plt == "Windows":&nbsp; &nbsp; cwd = os.path.join("<path to file>", "start.py")&nbsp; &nbsp; os.system('{} {}'.format('python', cwd))elif plt == "Linux":&nbsp; &nbsp; cwd = os.path.join("<path to file>", "start.py")&nbsp; &nbsp; os.system('{} {}'.format('python3', cwd))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python