【发布时间】:2021-08-24 17:20:28
【问题描述】:
我有一个示例 html 文档。
html_doc = '''<html><body><div>
<h5>This is my heading 1</h5>
<p>I have some content here</p>
I am point one.\n\nI am point two.
<h5>Some more text here</h5> Some more text outside a tag.</div></body></html>'''
我正在尝试从 html 标签之外的第 4 行和第 5 行中提取文本并将其转换为 p 标签元素。这个我试过了-
from bs4.element import NavigableString
soup = BeautifulSoup(html_doc, 'html.parser')
div_tags = soup.div
for idx in range(len(div_tag.contents)):
if type(div_tag.contents[idx]) == NavigableString:
count = 0
for a_str in div_tag.contents[idx].split('\n'):
if a_str == '':
continue
else:
count +=1
tag = parsed_html.new_tag("p")
tag.string = a_str
div_tag.contents[idx+count].insert_before(tag)
使用上面的代码,我无法将最后一个 NavigableString 转换为 p 标签。此外, NavigableString 的先前文本保留在树中。但所需的输出是 -
<html><body><div>
<h5>This is my heading 1</h5>
<p>I have some content here</p>
<p>I am point one.<\p>
<p>I am point two.<\p>
<h5>Some more text here</h5>
<p>Some more text outside a tag.
</p></div></body></html>
【问题讨论】:
标签: python html beautifulsoup