Python爬虫获取href报错:AttributeError: 'NoneType' object has no attribute 'get'
问题解决:AttributeError: 'NoneType' object has no attribute 'get'
你的问题出在重复查找的逻辑错误上:
soup.find_all('a', {'class':'Lwqic Cj b'})已经把所有符合这个class的a标签都抓取到website列表里了,遍历的时候每个site本身就是你要找的目标a标签对象。- 你在循环里又用
site.find('a', {'class':'Lwqic Cj b'})去查找子标签,而这些a标签内部并没有同样class的子a标签,所以find返回了None,调用get自然就触发了AttributeError。
修正后的代码直接从当前a标签提取href即可:
website = soup.find_all('a', {'class':'Lwqic Cj b'}) for site in website: # 直接获取当前a标签的href属性 url = site.get('href') # 可选:过滤掉没有href的无效标签 if url: print(url)
额外提示:如果怕某些a标签没有href属性,还可以用带默认值的写法避免意外报错:
url = site.get('href', default=None)
内容的提问来源于stack exchange,提问作者Code Ninja
相关产品推荐
相关产品推荐

