BeautifulSoup:AttributeError:'NavigableString'对象没有属性'name'

Zey*_*nel 16 python beautifulsoup

你知道为什么BeautifulSoup教程中的第一个例子http://www.crummy.com/software/BeautifulSoup/documentation.html#QuickStart给出了AttributeError: 'NavigableString' object has no attribute 'name'吗?根据这个答案,HTML中的空格字符会导致问题.我尝试了几页的来源和1个工作,其他人给出了同样的错误(我删除了空格).你能解释"名称"所指的是什么以及为什么会发生这种错误吗?谢谢.

Mat*_*odd 20

name如果对象是Tag对象,则将引用标记的名称(即:<html>name ="html")

如果节点之间的标记中有空格,BeautifulSoup会把它们变成NavigableString's.因此,如果你使用contents抓取节点的索引,你可能会抓住NavigableString而不是下一个Tag.

要避免这种情况,请查询您要查找的节点:搜索解析树

或者如果你知道你想要的下一个标签的名称,你可以使用该名称作为属性,它将返回Tag带有该名称的第一个名称,或者None如果不存在具有该名称的子项:使用标记名称作为成员

如果你想使用它,contents你必须检查你正在使用的对象.您获得的错误只是意味着您正在尝试访问name属性,因为代码假定它是aTag


Max*_*ysh 9

NavigableString在迭代树时忽略对象:

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

for body_child in soup.body.children:
    if isinstance(body_child, NavigableString):
        continue
    if isinstance(body_child, Tag):
        print(body_child.name)
Run Code Online (Sandbox Code Playgroud)

  • .find_all()似乎只返回子标签并忽略空格... (3认同)

Tom*_*tor 7

您可以使用try catch来消除在循环中解析Navigable String时的情况,如下所示:

    for j in soup.find_all(...)
        try:
            print j.find(...)
        except NavigableString: 
            pass
Run Code Online (Sandbox Code Playgroud)

  • 我得到: except NavigableString: TypeError: 使用此方法时不允许捕获不从 BaseException 继承的类 (2认同)