【发布时间】:2017-06-21 14:59:14
【问题描述】:
我需要你的帮助:我有 <p> 标签和许多其他标签,如下例所示:
<p>I <strong>AM</strong> a <i>text</i>.</p>
我只想得到“我是一个文本”,所以我 unwrap() 标签 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() 连接起来?
【问题讨论】:
-
你应该取消
p... -
我准确地说,我需要将父母(在我的情况下,P)保留在我的汤中,因为我需要知道我提取的文本所在的标签。
标签: python beautifulsoup