scrapy vscode调试python scrappy未单步执行回调函数

k7fdbhmy  于 2022-12-13  发布在  Vscode
关注(0)|答案(3)|浏览(120)

测试爬网程序:

class QuotesSpider(scrapy.Spider):
name = "quotes"

def start_requests(self):
    urls = [
        'http://quotes.toscrape.com/page/1/',
        'http://quotes.toscrape.com/page/2/',
    ]
    for url in urls:
        yield scrapy.Request(url=url, callback=self.parse)

def parse(self, response):
    page = response.url.split("/")[-2]
    filename = 'quotes-%s.html' % page
    with open(filename, 'wb') as f:
        f.write(response.body)
    self.log('Saved file %s' % filename)

我写了一个main.py:

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy","crawl","quotes"])

并且我添加了python scrapy调试器配置,一切都很好,直到hit yield scrapy.request(url=url,callback= self.parse)它没有进入回调解析函数?

3wabscal

3wabscal1#

好了,现在我知道为什么了,因为yield请求是异步的,并且回调将在子线程返回结果之后被调用,所以等待一段时间,它将最终调试到parse函数中

8aqjt8rx

8aqjt8rx2#

您确定您的parse函式是在类别内吗?这个程式码片段看起来像是您有错误的缩排。

hsgswve4

hsgswve43#

我在调试回调函数时遇到了同样的问题。
我在回调函数中添加了breakpoint(),它可以再次调试。

def parse(self, response):
    breakpoint()
    page = response.url.split("/")[-2]
    filename = 'quotes-%s.html' % page
    with open(filename, 'wb') as f:
        f.write(response.body)
    self.log('Saved file %s' % filename)

相关问题