bs4发生KeyError:返回self.attrs [key]

问题描述

我有一些有效的代码,但是最近开始给我一个错误。有问题的代码部分如下所示:

if(new_hash != old_hash):
        print(new_hash)
        print(old_hash)
        # Finds content of the most recent post on the list
        content = BeautifulSoup(vf_html.find('description').findNext('description').find(text=lambda t: isinstance(t,CData)),'html.parser')
        for img in content.select('img'):
            img.replace_with(img['alt'])
        content = content.text
        new_content_hash = hashlib.md5(str(content).encode('utf-8')).hexdigest()
        toSend = (content[:1000] + '') if len(content) > 75 else content
        # Finds author of the most recent post on the list
        author = vf_xml.find('creator').get_text(strip=True)
        author = author.split()[0]
        author = author[1:]

这工作正常,但是几个小时前它开始向我抛出此错误:

Traceback (most recent call last):
  File "C:\Users\Taran Mayer\Desktop\CodyBot\scrape.py",line 160,in <module>
    scrape()
  File "C:\Users\Taran Mayer\Desktop\CodyBot\scrape.py",line 83,in scrape
    img.replace_with(img['alt'])
  File "C:\Python38\lib\site-packages\bs4\element.py",line 1401,in __getitem__
    return self.attrs[key]
KeyError: 'alt'

我认为我没有进行任何更改,并且尝试恢复到该代码的早期有效版本,但是该错误仍然存​​在。有人可以帮我找出我在做错什么吗?如果我注释掉这些行

for img in content.select('img'):
    img.replace_with(img['alt'])

该程序可以运行,但不能满足我的要求。

解决方法

您似乎想要.replace_with的某些图像没有alt=属性。

您可以使用以下方法解决该问题:

for img in content.select('img'):
    img.replace_with(img.attrs.get('alt',''))

这将替换所有图像(甚至是缺少alt=...属性的图像)


或者:

for img in content.select('img[alt]'):
    img.replace_with(img['alt'])

这将仅替换具有alt=...属性的图像。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...