python - 将额外的参数传递给 scrapy.Request()

标签 python scrapy

实际上我想将与特定网站相关的所有数据(文本、hrefs、图像)存储到一个文件夹中。为了做到这一点,我需要将该文件夹的路径传递给所有不同的解析函数。所以我想像这样在 scrapy.Request() 中将此路径作为额外的 kwargs 传递:

yield scrapy.Request(url=url,dont_filter=True, callback=self.parse,errback = self.errback_function,kwargs={'path': '/path/to_folder'})

但它给出错误 TypeError: __init__() got an unexpected keyword argument 'kwargs'

如何将该路径传递给下一个函数?

最佳答案

对于任何可能需要它的人......

您可以像这样使用 meta 参数来传递额外的参数...

   yield scrapy.Request(url=url,dont_filter=True, 
callback=self.parse,errback = self.errback_function,  meta={'filepath': filepath})

更新:

Request.cb_kwargs was introduced in version 1.7. Prior to that, using Request.meta was recommended for passing information around callbacks. After 1.7, Request.cb_kwargs became the preferred way for handling user information, leaving Request.meta for communication with components like middlewares and extensions.

因此对于 >= 1.7 的版本,以下是可行的:

   request = scrapy.Request('http://www.example.com/index.html',
                             callback=self.parse_page2,
                             cb_kwargs=dict(main_url=response.url))

你可以引用这个文档:https://doc.scrapy.org/en/latest/topics/request-response.html#passing-additional-data-to-callback-functions

关于python - 将额外的参数传递给 scrapy.Request(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46579130/

相关文章:

python - 操作系统错误 : raw write() returned invalid length when using print() in python

python - 在 Python 中分析时间序列 - pandas 格式错误 - statsmodels

python - 使用 scrapy : defining path to Django project 访问 Django 模型

python - Scrapy 中的验证码

python - Scrapy在使用crawlerprocess运行时抛出错误

python - 无法导入 Scrapy 的设置模块或其 scrapy.cfg

Python:使用循环将行添加到现有数据框中

python - 如何在不离开的情况下使用 qpython 中的脚本

python - 我的 Py_NoneStruct 符号(python、boost.python)在哪里?

javascript - 如何抓取无限滚动的网站?