【问题标题】:Keyerror with bs4: return self.attrs[key]bs4 的 Keyerror:返回 self.attrs[key]
【发布时间】:2020-12-23 04:54:56
【问题描述】:

我有一些可以运行的代码,但最近开始出现错误。有问题的代码部分如下所示:

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'])

程序可以运行,但没有按照我的意愿运行。

【问题讨论】:

    标签: python beautifulsoup urllib


    【解决方案1】:

    您想.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=... 属性的图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 2021-04-27
      相关资源
      最近更新 更多