Skip to main content
 首页 » 编程设计

python之unwrap() 后使用 beautifulSoup 获取真实文本

2024年10月01日7kenshinobiy

我需要你的帮助:我有 <p>在下面的示例中使用许多其他标签进行标记:

<p>I <strong>AM</strong> a <i>text</i>.</p> 

我只想得到“我是一个文本”,所以我解包()标签strong和 i 使用以下代码:

for elem in soup.find_all(['strong', 'i']): 
    elem.unwrap() 

接下来,如果我打印 soup.p一切都很好,但是如果我不知道我的字符串所在的标签的名称,问题就开始了!

下面的代码应该更清晰:

from bs4 import BeautifulSoup 
 
html = ''' 
<html> 
    <header></header> 
    <body> 
        <p>I <strong>AM</strong> a <i>text</i>.</p> 
    </body> 
</html> 
''' 
soup = BeautifulSoup(html, 'lxml') 
 
for elem in soup.find_all(['strong', 'i']): 
    elem.unwrap() 
 
print soup.p  
# output : 
# <p>I AM a text.</p> 
 
for s in soup.stripped_strings: 
    print s 
# output  
 
''' 
I 
AM 
a 
text 
. 
''' 

为什么 BeautifulSoup 将我所有的字符串分开,而我之前将它与我的 unwrap() 连接起来?

请您参考如下方法:

如果你 .unwrap() 标签,您删除标签,并将内容放入父标签。但是文本没有合并,因此,您获得了一个列表NavigableString s(str 的子类):

>>> [(c,type(c)) for c in soup.p.children] 
[('I ', <class 'bs4.element.NavigableString'>), ('AM', <class 'bs4.element.NavigableString'>), (' a ', <class 'bs4.element.NavigableString'>), ('text', <class 'bs4.element.NavigableString'>), ('.', <class 'bs4.element.NavigableString'>)] 

因此,这些元素中的每一个都是一个分隔 文本元素。因此,尽管您删除了标签本身并注入(inject)了文本,但这些字符串并没有连接起来。这似乎合乎逻辑,因为左边和右边的元素可能仍然是标签:通过展开 <strong>你还没有打开包裹<i>同时。

但是您可以使用 .text , 获取全文:

>>> soup.p.get_text() 
'I AM a text.' 

或者您可以决定 join元素在一起:

>>> ''.join(soup.p.strings) 
'I AM a text.'