【问题标题】:BS4 replace_with for replacing with new tagBS4 replace_with 用新标签替换
【发布时间】:2020-08-14 20:15:49
【问题描述】:

我需要在 html 文件中找到某些单词并用链接替换它们。结果应该是该文件(由浏览器显示)允许您像往常一样单击链接。 Beautiful Soup 会自动转义标签。我怎样才能避免这种行为?

最小的例子

#!/usr/bin/env python3
from bs4 import BeautifulSoup
import re

html = \
'''
   Identify
'''
soup = BeautifulSoup(html,features="html.parser")
for txt in soup.findAll(text=True):
  if re.search('identi',txt,re.I) and txt.parent.name != 'a':
    newtext = re.sub('identify', '<a href="test.html"> test </a>', txt.lower())
    txt.replace_with(newtext)
print(soup)

结果:

&lt;a href="test.html"&gt; test &lt;/a&gt;

预期结果:

<a href="test.html"> test </a>

【问题讨论】:

    标签: python beautifulsoup replacewith


    【解决方案1】:

    您可以将带有标记的新汤作为.replace_with()的参数,例如:

    import re
    from bs4 import BeautifulSoup
    
    
    html = '''
       Other Identify Other
    '''
    soup = BeautifulSoup(html,features="html.parser")
    for txt in soup.findAll(text=True):
      if re.search('identi',txt,re.I) and txt.parent.name != 'a':
        new_txt = re.sub(r'identi[^\s]*', '<a href="test.html">test</a>', txt, flags=re.I)
        txt.replace_with(BeautifulSoup(new_txt, 'html.parser'))
    
    print(soup)
    

    打印:

       Other <a href="test.html">test</a> Other
    

    【讨论】:

    • 谢谢!它就像一个魅力。我很早就有这个解决方案,但在遇到另一个问题时就放弃了。
    【解决方案2】:

    您可以使用 w3lib,它的 replace_entities() 函数来替换字符串中的 HTML 实体。

    要安装:pip install w3lib

    from bs4 import BeautifulSoup
    import re
    from w3lib.html import replace_entities
    html = \
    '''
       Identify
    '''
    soup = BeautifulSoup(html,features="html.parser")
    for txt in soup.findAll(text=True):
      if re.search('identi',txt,re.I) and txt.parent.name != 'a':
        newtext = re.sub('identify', r'<a href="test.html"> test </a>', txt.lower())
        txt.replace_with(newtext)
    
    print(replace_entities(str(soup))) #str(soup) as its BeautifulSoup type not str
    
    #Output
    >>> <a href="test.html"> test </a>
    

    【讨论】:

    • 非常感谢!虽然您的解决方案可能也有效,但 Andrej 的解决方案不需要额外的导入,所以我更喜欢他的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多