Dan*_*any 5 python beautifulsoup
我有点困惑:所有标签都有一种decompose()方法可以将标签从树中移除。但是如果我想删除 aNavigableString呢?它没有这样的方法:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
有一种方法我设法NavigableString从树中删除了:通过从内容列表中删除它:
>>> b.p.contents.pop(0)
'aaaa '
>>> b
<p><span> bbbbb </span> ccccc</p>
Run Code Online (Sandbox Code Playgroud)
问题是它仍然存在于strings方法响应中:
>>> list(b.strings)
['aaaa ', ' bbbbb ', ' ccccc']
Run Code Online (Sandbox Code Playgroud)
这表明这是错误的做法。此外,我strings在我的代码中使用,所以这个 hacky 解决方案是不可接受的,唉。
所以问题是:如何NavigableString从树中删除特定对象?
使用extract()代替decompose()
extract() 从树中删除标签或字符串。
decompose() 从树中删除一个标签。
b = BeautifulSoup('<p>aaaa <span> bbbbb </span> ccccc</p>', 'html.parser')
b.p.contents[0].extract()
print(b)
Run Code Online (Sandbox Code Playgroud)
要了解更多信息,请查看以下链接,您可以在其中找到更多详细信息。 美汤
| 归档时间: |
|
| 查看次数: |
973 次 |
| 最近记录: |