首页 > 解决方案 > BeatuifulSoup 解析逻辑 - 在运行代码之前检查图像是否存在

问题描述

我正在使用 scraperapi.com 和 Bs4 从网站上抓取网址,当它找不到特定元素时,它会使整个代码崩溃

有问题的行是我用来提取图像 src 的行

image = soup.find('img')['src']

我知道我需要在抓取它之前添加一个检查以查看它是否存在,例如

        return image[src]
    return ''```

but it doesn't seem to work, can anyone advise what i'm doing wrong?

标签: pythonweb-scrapingbeautifulsoup

解决方案


您可以简单地将导致问题的代码包装到 try 和 except 块中。这样你的代码应该继续执行。

try:
    image = soup.find('img')['src']
except:
    image = None

推荐阅读