如果使用 beautifulsoup 的 get_text() 方法返回空字符串,则可能是因为被解析的 HTML 中包含注释,而方法默认会忽略注释。可以通过在调用 get_text() 方法时添加参数 strip=False,即 get_text(strip=False),来获取包含注释的文本。以下是一个示例代码:
from bs4 import BeautifulSoup
html = ' Hello world!
'
soup = BeautifulSoup(html, 'html.parser')
# 默认情况下,get_text() 方法会忽略注释
text1 = soup.body.get_text()
print(text1) # 输出 ''
# 添加参数 strip=False,来获取包含注释的文本
text2 = soup.body.get_text(strip=False)
print(text2) # 输出 '\n This is a comment Hello world!\n'