首页 > 解决方案 > 如何捕获“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 标签的错误?

标签: pythonpython-3.xbeautifulsoup

解决方案


我尚未测试代码,但您可以在列表理解中添加一个条件,如下所示:

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内置函数。


推荐阅读