注意:,我已经通过了刮痕教程,我只是想知道fetch是如何工作的。
使用scrapy shell,这段代码运行良好。
>>> import scrapy
>>> url = 'http://quotes.toscrape.com/page/1/'
>>> def parse(response):
... print('parse %s' % response)
...
>>> req = scrapy.Request(url=url, callback=parse)
>>> fetch(req)这让我
2020-07-03 05:21:04 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)
2020-07-03 05:21:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None)
parse <200 http://quotes.toscrape.com/page/1/>如何在.py文件中运行?
我将代码放入fetch_req.py文件并使用以下命令运行该文件
python fetch_req.py然后我得到了
NameError:未定义名称'fetch‘
我理解这一点,因为fetch是scrapy.shell.Shell instance的一种方法,所以我将它添加到fetch_req.py中。
from scrapy import shell
shell.Shell.fetch(req)然后我得到了
TypeError Traceback (most recent call last)
<ipython-input-34-914d5e1bbfe3> in <module>()
----> 1 shell.Shell.fetch(req)
TypeError: fetch() missing 1 required positional argument: 'request_or_url'我用谷歌搜索错误,但没有击中。我该怎么解决这个问题?
发布于 2020-07-02 23:50:11
您必须对请求进行yield,以便scrapy引擎将其放入队列并执行请求。
要更好地理解这一点,您应该遵循@Gallaecio的建议,并遵循scrapy的教程。很简单。
编辑
我现在明白了你的意思,但是我不明白你为什么要用这种方式使用刮痕。当然,fetch方法并没有为此设计。
无论如何,问题在于您正在调用fetch,就好像它是一个静态方法。
from scrapy import shell
shell.Shell.fetch(req)您应该实例化对象,然后从对象调用方法。之所以会引发缺少的必需参数,是因为它期望self和request_or_url作为参数。
您还可以尝试将类作为第一个参数传递。(就像类方法一样)
不过,这可能会导致新的例外情况。
https://stackoverflow.com/questions/62705454
复制相似问题