我有两个类似这样的HTML:
<h3>
First heading
</h3>
<ol>
<li>
hi
</li>
</ol>
<h3>
Second
</h3>
<ol>
<li>
second
</li>
</ol>
文件2
<h3>
First heading
</h3>
<ol>
<li>
hello
</li>
</ol>
<h3>
Second
</h3>
<ol>
<li>
second to second
</li>
</ol>
我需要将第二个文档中的li附加到相关h3下第一个文档的html中。 这是我的密码
soup = BeautifulSoup(html_string)
h3_tags = soup.find_all('h3')
ol_tags = [each_h3.find_next('ol') for each_h3 in h3_tags]
soup = BeautifulSoup(html_string_new)
h3_tags_new = soup.find_all('h3')
ol_tags_new = [each_h3.find_next('ol') for each_h3 in h3_tags_new]
countries_old = []
countries_new = []
html_new = ""
for i in h3_tags:
countries_old.append(i.text)
for i in h3_tags_new:
countries_new.append(i.text)
for country in countries_new:
idx = countries_old.index(country)
tag = str(ol_tags[idx])
tag = tag[:-5]
tag = tag[4:]
idx_new = countries_new.index(country)
tag_new = str(ol_tags_new[idx_new])
tag_new = tag_new[:-5]
tag_new = tag_new[4:]
tag = "<ol>" + tag + tag_new + "</ol>"
ol_tags[idx] = tag
html_new += h3_tags[idx]
html_new += tag
with open("check.html", "w", encoding="utf8") as html_file:
html_file.write(html_new)
html_file.close()
import pypandoc
output = pypandoc.convert(source='check.html', format='html', to='docx', outputfile='test.docx', extra_args=["-M2GB", "+RTS", "-K64m", "-RTS"])
此代码从第二个文档的索引中获取h3,并从同一索引中获取第二个文档的ol值。然后,它从这些标签中删除ol标签,并将这两个标签连接在一起。它一直将这些存储在html_文件中。但当我将ol与h3连接起来时,会出现以下错误:
TypeError: can only concatenate str (not "Tag") to str
编辑: 预期产出:
<h3>
First heading
</h3>
<ol>
<li>
hello
</li>
<li>
hi
</li>
</ol>
<h3>
Second
</h3>
<ol>
<li>
second to second
</li>
<li>
second
</li>
</ol>
尝试:
印刷品:
相关问题 更多 >
编程相关推荐