Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何抓住';非类型';对象没有属性';获取';综合清单_Python_Python 3.x_Beautifulsoup - Fatal编程技术网

Python 如何抓住';非类型';对象没有属性';获取';综合清单

Python 如何抓住';非类型';对象没有属性';获取';综合清单,python,python-3.x,beautifulsoup,Python,Python 3.x,Beautifulsoup,我想从网站上抓取URL。我用的是beautifulsoup4 我要刮的结构是这样的: 我使用的代码如下: 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'

我想从网站上抓取URL。我用的是beautifulsoup4

我要刮的结构是这样的:

我使用的代码如下:

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>
然后,我收到一个错误,即a不存在:

'NoneType' object has no attribute 'a'
由于我是Python的新手,我不知道如何处理这个错误。我本以为会有一个警告,其中一些元素没有p/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内置函数。

在综合列表中添加双if语句,以检查它是否具有“p”和“a”属性,从而解决了问题:

all_urls = [x.p.a.get('href') for x in soup.findAll("div", class_="b-accordion__text") if x.p and x.p.a]

all_url=[x.p.a.get('href')表示汤中的x.findAll(“div”,class=“b-accordion\uu text”),如果x.p.a]
。虽然我对python不是太陌生,但如果不幸的是x.p.a@shahkalpesh无法工作,这应该会有所帮助。我已经在原始帖子中添加了这个。哎呀,如果x.p与原始帖子中@shahkalpesh的评论相同,那么应该是
。仍然不起作用。
all_urls = [x.p.a.get('href') for x in soup.findAll("div", class_="b-accordion__text") if x.p and x.p.a]