Python 刮擦执行流

Python 刮擦执行流,python,scrapy,Python,Scrapy,我试图理解“刮”执行,但由于其间使用的生成器而感到困惑。我对生成器知之甚少,但我无法在这里可视化/关联这些东西 下面是scrapy文档中的代码 问题 1) 这里的产量是如何运作的 2) 我在parse函数中看到两个for循环,第一个for循环在yield中调用parse\u author函数,但只有在for-loop1(执行两次)和loop2(执行一次)之后才被调用。有人能解释一下执行流程是如何发生的吗 import scrapy from datetime import datetime, t

我试图理解“刮”执行,但由于其间使用的生成器而感到困惑。我对生成器知之甚少,但我无法在这里可视化/关联这些东西

下面是scrapy文档中的代码

问题

1) 这里的产量是如何运作的

2) 我在parse函数中看到两个for循环,第一个for循环在yield中调用parse\u author函数,但只有在for-loop1(执行两次)和loop2(执行一次)之后才被调用。有人能解释一下执行流程是如何发生的吗

import scrapy
from datetime import datetime, timedelta
name = 'prox-reveal'
start_urls = ['http://quotes.toscrape.com/']
def parse(self, response):
    # follow links to author pages
    for href in response.css('.author + a::attr(href)'):
        print('1---------->{}'.format(datetime.now().strftime('%Y%m%d_%H%M%S-%f')))
        yield response.follow(href, self.parse_author)

    # follow pagination links
    for href in response.css('li.next a::attr(href)'):
        print('2---------->{}'.format(datetime.now().strftime('%Y%m%d_%H%M%S-%f')))
        yield response.follow(href, self.parse)

def parse_author(self, response):
    print('3---------->{}'.format(datetime.now().strftime('%Y%m%d_%H%M%S-%f')))
    def extract_with_css(query):
        return response.css(query).extract_first().strip()

    yield {
        'name': extract_with_css('h3.author-title::text'),
        'birthdate': extract_with_css('.author-born-date::text'),
        'bio': extract_with_css('.author-description::text'),
    }

感谢

对请求及其回调之间关系的简化概述:

  • 创建一个
    请求
    对象,并将其传递给Scrapy的引擎进行进一步处理

    yield response.follow(href, self.parse_author)
    
  • 下载请求的网页并创建
    响应
    对象

  • 使用创建的响应调用请求的回调(
    parse_author()

现在是我认为给你带来麻烦的部分

Scrapy是一个异步框架,它可以在等待I/O操作(如下载网页)完成时做其他事情


因此,您的循环将继续,其他请求将被创建和处理,并且回调将被调用—只要数据可用。

感谢您的解释,现在就有意义了。然而,我仍然不明白产量是如何工作的。据我所知,下一个命令应该在那里,以便任何让步都能发挥作用。我错过了什么吗?。再次感谢这里需要知道的一件重要事情是,您只编写了正在执行的代码的一小部分,而大部分细节以及代码的实际执行都由框架处理。因此,在scrapy本身的代码中可能有一个
next
(或for循环)。@stranac——正确且确信,非常感谢。我的意图是请求人们帮助理解我遗漏的一些明显(如果有的话)的东西。