这个错误是因为您试图将BeautifulSoup对象直接写入文件,但是write()方法需要的是一个字符串。您可以使用str(soup) 将BeautifulSoup对象转换为字符串后再写入文件。
以下是修改后的代码:
from bs4 import BeautifulSoup
# 创建一个空白的HTML文档
html = "<html><body></body></html>"
# 使用BeautifulSoup解析HTML文档
soup = BeautifulSoup(html, 'html.parser')
# 创建<li>标签及其子元素
li_tag = soup.new_tag("li")
a_tag = soup.new_tag("a", href="?r=compasstiebaApp/index")
i_tag = soup.new_tag("i", class_="icon-tag")
span_tag = soup.new_tag("span", class_="menu-text")
# 设置<span>标签的内容
span_tag.string = "tiebase"
# 将子元素添加到父元素中
a_tag.append(i_tag)
a_tag.append(span_tag)
li_tag.append(a_tag)
# 找到适当的位置,将新标签插入其中(例如,在<body>标签内部最后一个位置)
body_tag = soup.find("body")
body_tag.append(li_tag)
# 将BeautifulSoup对象转换为字符串
output_html = str(soup)
# 将结果写入文件
with open("output.html", "w") as f:
f.write(output_html)
执行上述代码后,您将得到一个名为output.html 的文件,其中包含了所需的HTML结构。<br/><br/><br/><p style="color:#CCCCCC;font-size:12px;">内容由零声教学AI助手提供,问题来源于学员提问</p> |