python - 如何捕获“NoneType”对象在综合列表中没有“get”属性
问题描述
我想从网站上抓取网址。我正在使用beautifulsoup4。
我试图抓取的结构是这样的: HTML Structure
我正在使用的代码是这样的:
soup = BeautifulSoup(response.text, "html.parser")
all_urls = [x.p.a.get('href') for x in soup.findAll("div", class_="b-accordion__text")]
当我运行脚本时,我收到以下错误:
'NoneType' object has no attribute 'get'
这可能是因为某些 div 是空的并且不包含 p/a,因此在不存在的对象上调用 get 函数。
<div class="b-accordion__text">
</div>
当我尝试添加一个 if 表达式时:
all_urls = [x.p.a.get('href') for x in soup.findAll("div", class_="b-accordion__text") if x.p.a]
然后我收到不存在的错误:
'NoneType' object has no attribute 'a'
由于我对 Python 非常陌生,我不知道如何处理这个错误。我本来预计会有一些元素没有 ap/a 并且脚本仍然会运行的警告。但它中止了。
问题:如何处理/捕获为空的 div 标签的错误?
解决方案
我尚未测试代码,但您可以在列表理解中添加一个条件,如下所示:
soup = BeautifulSoup(response.text, "html.parser")
all_urls = [x.p.a.get('href') for x in soup.findAll("div", class_="b-accordion__text") if not x.p.a is None]
更一般地,要测试特定属性,您可以使用hasattr内置函数。
推荐阅读
- ios - 如何在 AppDelegate.swift 中使用 Firebase 远程配置?
- mongodb - 如何替换多次出现的短语mongodb
- sql-server - 使用 T-SQL 在文本文件中执行操作
- c# - 为什么将单个实体保存到我的 EF Core 数据库上下文会导致多次插入?
- c# - 最小化表单时,Numericupdown 箭头变黑
- c++ - 为什么将 unique_ptr 的 std::move() 到 void 函数来重置指针比调用显式 unique_ptr.reset() 花费的时间更少
- node.js - 从我的数据库中提取数据并将其(ById)填充到我的 Vue 视图(使用 Axios)时出现问题。后端是 Node/Express
- javascript - 如何获取命令发送到的频道名称
- python - driver.find_elements_by_xpath 随机失败
- android - 使用 Observable Boolean 设置 android 视图的可见性