这个问题通常是由于在HTML标记中使用了 < 实体引用所致。为了避免这个问题,可以在BeautifulSoup构造函数中指定解析器为'html.parser',如下所示:
from bs4 import BeautifulSoup
html = 'Some text < some more text
'
soup = BeautifulSoup(html, 'html.parser')
text = soup.find('p').decode_contents()
print(text)
输出: Some text < some more text
在这个例子中,我们指定了'html.parser'解析器,并使用find()方法找到了包含文本的p标签。我们然后调用了decode_contents()方法来解码所有HTML实体引用。最终输出的文本包含实体引用 < 而非 <,解决了我们遇到的问题。