我在使用scrapy时遇到的
我在通过items传递数据给管道时,发现不管怎么处理author,它都会报KeyError的错误,但是它里面是非空的
2022-12-25 15:55:54 [scrapy.core.scraper] ERROR: Error processing {'PMID': '11180764',
'author': 'Tsuda H H.',
'citation': 'Breast Cancer. 2001;8(1):38-44. doi: 10.1007/BF02967476.',
'resources': 'Review.',
'title': 'Prognostic and predictive value of c-erbB-2 (HER-2/neu) gene '
'amplification in human breast cancer.'}
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\twisted\internet\defer.py", line 892, in _runCallbacks
current.result = callback( # type: ignore[misc]
File "C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\scrapy\utils\defer.py", line 285, in f
return deferred_from_coro(coro_f(*coro_args, **coro_kwargs))
File "C:\Users\Administrator\PycharmProjects\pythonProject\pubmed\pubmed\pipelines.py", line 14, in process_item
author = item['auther']
File "C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\scrapy\item.py", line 79, in __getitem__
return self._values[key]
KeyError: 'auther'
我尝试了把数据变为byte格式,或者替换其中的拉丁字符,都报同样的错误
在代码中,你使用了 author = item['auther'] 语句来获取 item 中的 author 字段。但是你的 item 中的字段是 author,而不是 auther。因此会出现 KeyError 错误。
你应该将该语句改为 author = item['author'],这样就可以正常获取 item 中的 author 字段了。
这个错误可能是由于items中的字段名称与你在使用时的字段名称不一致导致的。
try:
author = item['author']
except KeyError:
print("Author field not found!")
author = None
多谢邀请,你的key名称应该是写错了,代码与数据不匹配。请修正auther的单词书写。
如截图: