小编Que*_*tin的帖子

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

我需要你的帮助:我有<p>带有许多其他标签的标签,如下例所示:

<p>I <strong>AM</strong> a <i>text</i>.</p>
Run Code Online (Sandbox Code Playgroud)

我只想得到“我是文本”,所以我 unwrap() 标签strongi 使用下面的代码:

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() …

python beautifulsoup

2
推荐指数
1
解决办法
2245
查看次数

标签 统计

beautifulsoup ×1

python ×1