美丽汤4 :需要添加反转段落标签,将一个字段分成两个段落



目前,有一个标头标签,它的内容附加在它上面。我需要通过将标题维护在单独的段落标签中来将标题与其内容分开。

block_tag = <p>1.1 <u>Header Information</u>.  Content of the header with multiple lines</p>
type(block_tag)
<class 'bs4.element.Tag'>

标头应包含在<b><u>标记中

预期成果:

block_tag
<p>1.1 <u>Header Information</u>.</p><p>  Content of the header with multiple lines</p>

到目前为止,我已经尝试使用

-new_tag("p") 创建<p></p>。需要反向标签<p><p>

方法-1

para_tag = soup.new_tag("p")
block_tag.insert(2,para_tag)
block_tag
<p>1.1 <u>Header Information</u>. <p></p> Content of the header with multiple lines</p>

方法-2

block_tag.insert(2,"<p><p>")
block_tag
<p>1.1 <u>Header Information</u>&lt;p&gt;&lt;p&gt;.  Content of the header with multiple lines</p>

谢谢

您可以在标头后获取剩余内容并将其包装在新的p标签中。然后从原始标签中提取它并insert_after原始标签。

from bs4 import BeautifulSoup
html="""
<p>1.1 <u>Header Information</u>.  Content of the header with multiple lines</p>
"""
soup=BeautifulSoup(html,'html.parser')
block_tag=soup.find('p')
remaining=block_tag.contents[-1]
new_tag=remaining.wrap(soup.new_tag("p"))
block_tag.insert_after(new_tag.extract())
print(soup)

输出:

<p>1.1 <u>Header Information</u></p><p>.  Content of the header with multiple lines</p>

除了句号,几乎完美。

注意: 我不确定Content of the header with multiple lines到底是什么,但不要将此视为确切的答案。你可能不得不即兴发挥。

相关内容

最新更新