我有点困惑:所有标记都有一个decompose()
方法,允许从树中删除标记。但是如果我想删除NavigableString
呢?它没有这样的方法:
>>> b = BeautifulSoup('<p>aaaa <span> bbbbb </span> ccccc</p>', 'html.parser')
>>> b.p.contents[0]
'aaaa '
>>> type(b.p.contents[0])
<class 'bs4.element.NavigableString'>
>>> b.p.contents[0].decompose()
Traceback (most recent call last):
...
AttributeError: 'NavigableString' object has no attribute 'decompose'
有一种方法可以从树中删除NavigableString
:从内容列表中删除它:
>>> b.p.contents.pop(0)
'aaaa '
>>> b
<p><span> bbbbb </span> ccccc</p>
问题是它仍然存在于strings
方法响应中:
>>> list(b.strings)
['aaaa ', ' bbbbb ', ' ccccc']
这说明这样做是错误的。此外,我在我的代码中使用strings
,所以这个黑客解决方案是不可接受的,唉。你知道吗
所以问题是:如何从树中删除特定的NavigableString
对象?你知道吗
用
extract()
代替decompose()
extract()
从树中删除标记或字符串。你知道吗decompose()
从树中删除标记。你知道吗要了解更多信息,请查看下面的链接,您将在那里找到更多详细信息。 BeautifulSoup
相关问题 更多 >
编程相关推荐