【问题标题】:Insert html string into BeautifulSoup object将 html 字符串插入 BeautifulSoup 对象
【发布时间】:2015-09-22 15:55:11
【问题描述】:

我正在尝试将 html 字符串插入 BeautifulSoup 对象。如果我直接插入它,bs4 会清理 html。如果获取 html 字符串并从中创建汤,并插入我在使用 find 函数时遇到问题。 SO 上的This post thread 建议插入 BeautifulSoup 对象可能会导致问题。我正在使用该帖子中的解决方案,并在每次插入时重新创建汤。

但肯定有更好的方法将 html 字符串插入汤中。

编辑:我将添加一些代码作为问题所在的示例

from bs4 import BeautifulSoup

mainSoup = BeautifulSoup("""
<html>
    <div class='first'></div>
    <div class='second'></div>
</html>
""")

extraSoup = BeautifulSoup('<span class="first-content"></span>')

tag = mainSoup.find(class_='first')
tag.insert(1, extraSoup)

print mainSoup.find(class_='second')
# prints None

【问题讨论】:

  • 你能展示一下你的html 和预期的结果吗?
  • @user3100115 如果有帮助,我添加了一些非常简单的代码作为示例。
  • 嗨,您是否找到了无需创建新标签的解决方案?

标签: python beautifulsoup


【解决方案1】:

最好的方法是创建一个新标签span 并将其插入您的mainSoup。这就是.new_tag 方法的用途。

In [34]: from bs4 import BeautifulSoup

In [35]: mainSoup = BeautifulSoup("""
   ....: <html>
   ....:     <div class='first'></div>
   ....:     <div class='second'></div>
   ....: </html>
   ....: """)

In [36]: tag = mainSoup.new_tag('span')

In [37]: tag.attrs['class'] = 'first-content'

In [38]: mainSoup.insert(1, tag)

In [39]: print(mainSoup.find(class_='second'))
<div class="second"></div>

【讨论】:

    【解决方案2】:

    如果您已经有一个 html 字符串,最简单的方法是插入另一个 BeautifulSoup 对象。

    from bs4 import BeautifulSoup
    
    doc = '''
    <div>
     test1
    </div>
    '''
    
    soup = BeautifulSoup(doc, 'html.parser')
    
    soup.div.append(BeautifulSoup('<div>insert1</div>', 'html.parser'))
    
    print soup.prettify()
    

    输出:

    <div>
     test1
    <div>
     insert1
    </div>
    </div>
    

    更新 1

    这个怎么样?想法是使用 BeautifulSoup 生成正确的 AST 节点(span 标签)。看起来这样可以避免“无”问题。

    import bs4
    from bs4 import BeautifulSoup
    
    mainSoup = BeautifulSoup("""
    <html>
        <div class='first'></div>
        <div class='second'></div>
    </html>
    """, 'html.parser')
    
    extraSoup = BeautifulSoup('<span class="first-content"></span>', 'html.parser')
    tag = mainSoup.find(class_='first')
    tag.insert(1, extraSoup.span)
    
    print mainSoup.find(class_='second')
    

    输出:

    <div class="second"></div>
    

    【讨论】:

    • 明确声明解析器有何不同?
    • 实际上,我们不仅在声明解析器,还在为插入的 html 创建一个全新的解析树。 BeautifulSoup(x) 不是一个标记,它实际上做了一个解析,结果是一个汤对象。
    • 对不起,如果这很粗鲁,您是否完整阅读了我的帖子?我已经提到我已经尝试插入一个 BeautifulSoup 对象并且它会导致问题。这就是我寻找更好方法的原因。
    • beautifulsoup4 版本 4.4.1 有问题 - 使用汤方法(任何)修改汤树时会损坏。解决方法是使用 html5lib 解析器,如 tag.append( BeautifulSoup('&lt;span class="first-content"&gt;&lt;/span&gt;', 'html5lib') )
    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2022-01-02
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多