这个错误通常是由于 Beautiful Soup 在尝试查找(find_all)一个不存在的标签或属性时,找不到相关内容而返回“None”,导致其无法继续解析。要解决这个问题,需要先检查所查询的标签或属性是否存在,可以使用“if”语句进行判断,避免 Beautiful Soup 查找不存在的内容。以下是一个示例代码:
html_doc = """
The Dormouse's story
Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
...
"""soup = BeautifulSoup(html_doc, 'html.parser') p_tags = soup.find_all("p") if p_tags: for p_tag in p_tags: print(p_tag.get("class")) else: print("没有找到 p 标签")
在上述代码中,首先用 Beautiful Soup 解析 HTML 文档,然后使用 find_all 方法查找所有的
标签。在“if”语句中,我们判断是否找到了
标签,如果找到了则打印每个标签的“class”属性,否则打印“没有找到 p 标签”提示信息。这样就能避免“NoneType”错误了。