python - 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?
解决方案
您可以简单地将导致问题的代码包装到 try 和 except 块中。这样你的代码应该继续执行。
try:
image = soup.find('img')['src']
except:
image = None
推荐阅读
- node.js - 尝试从 Heroku 部署的 Angular Api 连接后端 Api 时出现 404 错误
- javascript - 设置输入值以获取变量
- transactions - 如何在 PostgreSQL 中实现 MSSQL 的 SAVE TRAN?
- reactjs - 带有嵌套类型的 Graphql 突变?
- javascript - 如何找出重定向的位置以及哪个控制器正在处理数据
- android - 一个信号代码通知在片段中不起作用
- windows - Windows Batch - 在具有特定名称的文件夹中查找图像文件
- r - 计算几何平均值时出错
- push-notification - 我们在哪里可以找到对 PWA 推送通知的声音支持?
- css - Django 静态文件(CSS)不与模板链接