在Visual Studio Code中调试Scrapy项目

24

我在Windows机上使用Visual Studio Code,正在编写一个新的Scrapy爬虫程序。这个爬虫程序已经可以正常工作了,但是我想要调试代码,因此我需要在launch.json文件中添加以下内容:

{
    "name": "Scrapy with Integrated Terminal/Console",
    "type": "python",
    "request": "launch",
    "stopOnEntry": true,
    "pythonPath": "${config:python.pythonPath}",
    "program": "C:/Users/neo/.virtualenvs/Gers-Crawler-77pVkqzP/Scripts/scrapy.exe",
    "cwd": "${workspaceRoot}",
    "args": [
        "crawl",
        "amazon",
        "-o",
        "amazon.json"
    ],
    "console": "integratedTerminal",
    "env": {},
    "envFile": "${workspaceRoot}/.env",
    "debugOptions": [
        "RedirectOutput"
    ]
}
但是我无法触发任何断点。 PS:我从这里获取了JSON脚本:http://www.stevetrefethen.com/blog/debugging-a-python-scrapy-project-in-vscode

可能是如何使用PyCharm调试Scrapy项目的重复问题。 - Lore
7个回答

45
为了执行典型的scrapy runspider <PYTHON_FILE>命令,您必须将以下配置设置到您的launch.json中:
{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Python: Launch Scrapy Spider",
            "type": "python",
            "request": "launch",
            "module": "scrapy",
            "args": [
                "runspider",
                "${file}"
            ],
            "console": "integratedTerminal"
        }
    ]
}

在任何你想要的位置设置断点,然后进行调试。


3
这应该是被认可的答案。在工作项目的 launch.json 中添加一个 scrapy 特定的配置是一个好的实践,易于实现,不需要创建额外的脚本。 - Andreas L.
@cpinamtz,出于某种原因,这似乎对我不起作用。我使用非常类似的设置,程序运行,但不会在断点处停止。 - Asif
@Asif 如果你正在使用多个爬虫,请检查你正在执行你期望调试的那一个。 - cpinamtz

22
在你的Scrapy项目文件夹中创建一个名为runner.py的模块,包含以下内容:
import os
from scrapy.cmdline import execute

os.chdir(os.path.dirname(os.path.realpath(__file__)))

try:
    execute(
        [
            'scrapy',
            'crawl',
            'SPIDER NAME',
            '-o',
            'out.json',
        ]
    )
except SystemExit:
    pass
  • 在您希望调试的行中放置断点

  • 使用VSCode调试器运行runner.py


  • 9

    请将您的json文件配置为以下内容:

    "version": "0.2.0",
    "configurations": [
        {
            "name": "Crawl with scrapy",
            "type": "python",
            "request": "launch",
            "module": "scrapy",
            "cwd": "${fileDirname}",
            "args": [
                "crawl",
                "<SPIDER NAME>"
            ],
            "console": "internalConsole"
        }
    ]
    

    点击VSCode中对应您的爬虫的选项卡,然后启动与json文件相对应的调试会话。


    1
    这个是最新的答案,因为它使用了最新的 Scrapy 爬取命令。 - Kenny Aires

    5

    您也可以尝试使用

    {
      "configurations": [
        {
            "name": "Python: Scrapy",
            "type": "python",
            "request": "launch",
            "module": "scrapy",
            "cwd": "${fileDirname}",
            "args": [
                "crawl",
                "${fileBasenameNoExtension}",
                "--loglevel=ERROR"
            ],
            "console": "integratedTerminal",
            "justMyCode": false
        }
      ]
    }
    

    但是字段的名称应该与爬虫的名称相同。

    --loglevel=ERROR用于获得输出的详细程度较少。 ;)


    为了让 crawl${fileBasenameNoExtension} 协同工作,请确保蜘蛛类的 name 属性与脚本文件的基本名称相同。 - omegastripes

    3
    我做到了。最简单的方法是创建一个运行脚本runner.py
    import scrapy
    from scrapy.crawler import CrawlerProcess
    
    from g4gscraper.spiders.g4gcrawler import G4GSpider
    
    process = CrawlerProcess({
        'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
        'FEED_FORMAT': 'json',
        'FEED_URI': 'data.json'
    })
    
    process.crawl(G4GSpider)
    process.start() # the script will block here until the crawling is finished
    

    我在这个文件中启动调试器时,为蜘蛛添加了断点。

    参考资料: https://doc.scrapy.org/en/latest/topics/practices.html

    2

    我使用了@fmango的代码并进行了改进。

    1. 不需要编写单独的运行文件,只需将这些代码行粘贴到爬虫的末尾即可。

    2. 运行Python调试器即可,就是这样。

    if __name__ == '__main__':
        import os
        from scrapy.cmdline import execute
    
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
    
        SPIDER_NAME = MySpider.name
        try:
            execute(
                [
                    'scrapy',
                    'crawl',
                    SPIDER_NAME,
                    '-s',
                    'FEED_EXPORT_ENCODING=utf-8',
                ]
            )
        except SystemExit:
            pass
    

    1
    不需要修改launch.json文件,使用默认的“Python:当前文件(集成终端)”即可完美运行。对于Python3项目,请记得将runner.py文件放在与scrapy.cfg文件(即项目根目录)相同的级别上。
    runner.py代码如@naqushab所示。请注意processs.crawl(className),其中className是您想要设置断点的蜘蛛类。

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接