如果您使用的是Beautiful Soup 4.x版本,请使用注释处理器将所有注释转换为HTML注释。可以如下处理:
from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(html, 'html.parser')
comments = soup.find_all(string=lambda text: isinstance(text, Comment))
for comment in comments:
comment.extract()
这个代码段将获取解析后所有注释并删除。如果您不需要删除注释可以将注释内部内容提取并转换为元素,操作如下:
for comment in comments:
new_element = soup.new_tag("p")
new_element.string = str(comment)
comment.replace_with(new_element)
在该代码片段中,新元素将与注释中的文本内容类似,保存为标签。您可以根据需要修改标记名称。