我需要你的帮助:我有<p>带有许多其他标签的标签,如下例所示:
<p>I <strong>AM</strong> a <i>text</i>.</p>
Run Code Online (Sandbox Code Playgroud)
我只想得到“我是文本”,所以我 unwrap() 标签strong并i
使用下面的代码:
for elem in soup.find_all(['strong', 'i']):
elem.unwrap()
Run Code Online (Sandbox Code Playgroud)
接下来,如果我打印一切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
.
'''
Run Code Online (Sandbox Code Playgroud)
为什么 BeautifulSoup 将我的所有字符串分开,而我之前将它与我的 unwrap() …