要解析BeautifulSoup返回带空格的文本,可以使用.stripped_strings
方法来获取文本内容,并使用join()
方法将其连接起来。
以下是一个示例代码:
from bs4 import BeautifulSoup
html = '''
This is some text.
Another paragraph.
'''
soup = BeautifulSoup(html, 'html.parser')
# 使用stripped_strings方法获取所有文本内容
text_list = [text for text in soup.stripped_strings]
# 使用join方法将文本连接起来
text_with_spaces = ' '.join(text_list)
print(text_with_spaces)
输出结果为:
This is some text. Another paragraph.
在上面的示例中,我们首先创建了一个包含HTML代码的字符串。然后,我们使用BeautifulSoup解析HTML,并使用.stripped_strings
方法获取所有的文本内容。最后,我们使用.join()
方法将这些文本内容连接成一个字符串,并将其打印出来。
注意:.stripped_strings
方法会自动去除文本前后的空白字符,但是保留元素内部的空格。