簡體   English   中英

Scrapy - 一次運行多個蜘蛛 - CrawlerProcess - 文件結構

[英]Scrapy - Running Multiple Spiders at Once - CrawlerProcess - File Structure

我正在嘗試使用 CrawlerProcess 一次運行多個 Scrapy 蜘蛛,但不確定文件結構。 當通過scrapy crawl indeedscrapy crawl monster (我的蜘蛛類的指定名稱)單獨運行時,兩個蜘蛛都能正常工作。

我目前的文件結構如下:

- scrapy
  - tutorial
    - spiders
      - __init__.py
      - indeed_spider.py
      - monster_spider.py
    - __init__.py
    - crawler.py
    - functions.py
    - items.py
    - middlewares.py
    - pipelines.py
    - settings.py
  - scrapy.cfg

如您所見,我在主教程目錄中設置了crawler.py

crawler.py的代碼如下:

from scrapy.crawler import CrawlerProcess
from tutorial.spiders.indeed_spider import IndeedSpider
from tutorial.spiders.monster_spider import MonsterSpider
from scrapy.utils.project import get_project_settings

settings = get_project_settings()
process = CrawlerProcess(settings)
process.crawl(IndeedSpider)
process.crawl(MonsterSpider)
process.start()

當我進入教程目錄並運行python crawler.py ,我收到以下錯誤消息:

Traceback (most recent call last):
  File "crawler.py", line 3, in <module>
    from tutorial.spiders.indeed_spider import IndeedSpider
ModuleNotFoundError: No module named 'tutorial'

這很奇怪,因為顯然有一個tutorial模塊。 Scrapy 文檔中沒有關於文件結構和一次運行多個蜘蛛的內容; 它給出了一個幫助不大的基本示例( 爬蟲文檔)。

我的問題是:

  • 如何在命令行上通過CrawlerProcess運行多個蜘蛛? 它不是scrapy crawl {spider_name} 我認為它是python crawler.py ,但鑒於我目前的結構,這不起作用。
  • crawler.py應該存放在項目目錄的什么位置?
  • 啟動CrawlerProcess是否需要進一步操作pipelines.pysettings.py

非常感謝你的幫忙!

你做對了,錯誤是關於 python 的導入執行。

Traceback (most recent call last):
  File "crawler.py", line 3, in <module>
    from tutorial.spiders.indeed_spider import IndeedSpider
ModuleNotFoundError: No module named 'tutorial'

這是 python 中眾所周知的障礙。 我建議你在scrapy的目錄中創建一個setup.py,代碼如下:

from setuptools import setup, find_packages

setup(name='nameofproject', version='version', packages=find_packages())

所以你的結構應該是:

> - scrapy
>   - setup.py
>   - tutorial
>     - spiders
>       - __init__.py
>       - indeed_spider.py
>       - monster_spider.py
>     - __init__.py
>     - crawler.py
>     - functions.py
>     - items.py
>     - middlewares.py
>     - pipelines.py
>     - settings.py
>   - scrapy.cfg

然后,您必須在您的 shell 中的 scrapy 目錄中執行以下命令:

pip install -e .

現在 python 的解釋器應該能夠將tutorial識別為一個模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM