BeautifulSoup报”AttributeError: ‘NavigableString’ object has no attribute ‘strip’ “异常的原因以及解决办法

  • Post category:Python

这个错误通常是在使用BeautifulSoup解析HTML文档时出现的,错误提示信息中包含类似”AttributeError: ‘NavigableString’ object has no attribute ‘strip'”的内容。它的原因是因为在HTML文档中,有的标签中并不是纯文本,而是一些空格、回车等特殊字符,这些特殊字符可能会被解析为NavigableString对象,而该对象并没有strip()方法来去除特殊字符。

解决该问题的办法主要有以下两种:

  1. 使用判断逻辑来确定当前处理的对象是否为NavigableString类型,如果是,则跳过操作。示例代码如下:
from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc, 'html.parser')
for tag in soup.find_all():
    if tag.string is not None and not isinstance(tag.string, str):
        continue
    # 进行自定义操作

该示例代码中,我们在进行自定义操作时,先判断了当前处理的对象是否为NavigableString类型,如果是,则跳过操作。

  1. 在调用strip()方法时,先将结果转换为字符串类型,示例代码如下:
from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc, 'html.parser')
for tag in soup.find_all():
    if tag.string is not None:
        string = str(tag.string).strip()
        # 进行自定义操作

该示例代码中,我们在调用strip()方法前,将结果先转换为字符串类型,然后进行去除特殊字符操作。

通过使用以上两种方法中的任意一种,我们就可以解决这个问题。