【问题标题】:Is there a way to replace text in NavigableString object to tag object in beautifulsoup?有没有办法将 NavigableString 对象中的文本替换为 beautifulsoup 中的标记对象?
【发布时间】: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


    【解决方案1】:

    您可以使用此示例将 html 标记之外的所有行包装到 &lt;p&gt;...&lt;/p&gt;

    from bs4 import BeautifulSoup, NavigableString
    
    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>"""
    
    soup = BeautifulSoup(html_doc, "html.parser")
    
    # root tag of the text:
    root_tag = soup.find("div")
    
    # replace all strings that are "outside" in the root tag:
    for c in root_tag.contents:
        if isinstance(c, NavigableString) and c.strip():
            to_replace = [
                "<p>{}</p>".format(line)
                for line in map(str.strip, c.split("\n"))
                if line
            ]
    
            c.replace_with(
                BeautifulSoup("\n" + "\n".join(to_replace) + "\n", "html.parser")
            )
    
    print(soup)
    

    打印:

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2011-12-10
      • 2016-03-31
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多