如何理解scrapy.Request中的回调函数?

How to understand callback function in scrapy.Request?

我正在阅读 Web Scraping with Python 2nd Ed,想使用 Scrapy 模块从网页中抓取信息。

我从文档中得到以下信息:https://docs.scrapy.org/en/latest/topics/request-response.html

callback (callable) – the function that will be called with the response of this request (once it’s downloaded) as its first parameter. For more information see Passing additional data to callback functions below. If a Request doesn’t specify a callback, the spider’s parse() method will be used. Note that if exceptions are raised during processing, errback is called instead.

我的理解是:

  1. 传入 url 并像我们在 requests 模块

    中那样获得响应

    resp = requests.get(url)

  2. 传递数据解析

    解析(响应)

问题是:

  1. 没看到resp是从哪里传入的
  2. 为什么需要在参数解析前加上 self 关键字
  3. self 关键字从未在解析函数中使用过,为什么要把它作为第一个参数?
  4. 我们可以像这样从响应参数中提取 url 吗:url = response.url 或者应该是 url = self.url
class ArticleSpider(scrapy.Spider):
    name='article'
    
    def start_requests(self):
        urls = [
        'http://en.wikipedia.org/wiki/Python_'
        '%28programming_language%29',
        'https://en.wikipedia.org/wiki/Functional_programming',
        'https://en.wikipedia.org/wiki/Monty_Python']

        return [scrapy.Request(url=url, callback=self.parse) for url in urls]
    

    def parse(self, response):
        url = response.url
        title = response.css('h1::text').extract_first()
        print('URL is: {}'.format(url))
        print('Title is: {}'.format(title))

有关 self 的信息,您可以在此处找到 - https://docs.python.org/3/tutorial/classes.html


关于这个问题:

can we extract URL from response parameter like this: url = response.url or should be url = self.url

您应该使用 response.url 获取当前 crawl/parse

页面的 URL

您似乎遗漏了一些与 python classes 和 OOP 相关的概念。阅读 python docs or at the very least this question.

是个好主意

这是 Scrapy 的工作原理,您实例化一个请求对象并将其交给 Scrapy 调度程序。

yield scrapy.Request(url=url) #or use return like you did

Scrapy 将处理请求,下载 html 并且它将 return 所有它得到的请求返回给回调函数。如果您没有在请求中设置回调函数(如我上面的示例),它将调用名为 parse.

的默认函数

Parse 是对象的一个​​方法(a.k.a 函数)。你在上面的代码中写了它,即使你没有它仍然会在那里,因为你的class继承了它的父class[的所有功能=18=]

class ArticleSpider(scrapy.Spider): # <<<<<<<< here
    name='article'

所以一个TL;您的问题的 DR:

1-你没有看到它,因为它发生在父级 class。

2-您需要使用 self. 以便 python 知道您正在引用蜘蛛实例的方法。

3-self参数是实例itself,被python.

使用

4-Response 是一个独立的对象,您的解析方法将其作为参数接收,因此您可以访问它的属性,例如 response.urlresponse.headers