如何将字符串转换为BeautifulSoup Tag对象解决HTML拼接报错问题
报错原因
你代码中html_new += h3_tags[idx]这行里,h3_tags[idx]是BeautifulSoup返回的Tag类型对象,不是字符串,不能直接和字符串类型的html_new拼接,这是触发TypeError的直接原因。
另外你手动截取ol标签字符串的逻辑容错性极低,一旦ol标签带属性(比如<ol class="xxx">),你的切片长度就会匹配错误,生成非法的HTML结构。
修正方案
直接用BeautifulSoup原生的节点操作方法实现需求,不用手动拼接字符串,更稳定:
from bs4 import BeautifulSoup import pypandoc # 加载两个HTML文档 soup_old = BeautifulSoup(html_string, 'html.parser') soup_new = BeautifulSoup(html_string_new, 'html.parser') # 构建旧文档h3文本到对应ol节点的映射 old_h3_map = {} for h3 in soup_old.find_all('h3'): h3_text = h3.get_text(strip=True) ol = h3.find_next('ol') old_h3_map[h3_text] = ol # 遍历新文档的h3,匹配后将li追加到旧文档的ol中 for h3_new in soup_new.find_all('h3'): h3_text = h3_new.get_text(strip=True) if h3_text not in old_h3_map: continue target_ol = old_h3_map[h3_text] ol_new = h3_new.find_next('ol') # 按预期把新文档的li插到旧li前面,如果要放后面把insert改成append即可 for li in reversed(ol_new.find_all('li')): target_ol.insert(0, li) # 直接用旧soup生成最终HTML,不需要手动拼接 final_html = str(soup_old) # 保存HTML并转docx with open("check.html", "w", encoding="utf8") as html_file: html_file.write(final_html) output = pypandoc.convert(source='check.html', format='html', to='docx', outputfile='test.docx', extra_args=["-M2GB", "+RTS", "-K64m", "-RTS"])
内容的提问来源于stack exchange,提问作者hannah montanna
相关产品推荐
相关产品推荐

