【问题标题】:Replace substring with <tag>substring</tag> in BeautifulSoup在 BeautifulSoup 中用 <tag>substring</tag> 替换子字符串
【发布时间】:2020-08-24 10:22:45
【问题描述】:

我正在尝试修改现有的 html 文件,以便将特定关键字打印为强(无论它们出现在哪里)。

我的尝试:

from bs4 import BeautifulSoup as soup
txt = """<html><head><style></style></head><body><h2>"This is my keyword</h2><table><tr><td>This could be another instance of the keyword.</td></tr></table></body></html>"""

buzz_words = ["keyword", "apples"]

htmlSoup = soup(txt, features="html.parser")
for word in buzz_words:
    target = htmlSoup.find_all(text=re.compile(r"" + re.escape(word)))
    for v in target:
        v.replace_with(v.replace(word, "".join(["<strong>", word, "</strong>"])))
print(str(htmlSoup))

结果:

This is my &lt ;strong&gt ;keyword&lt ;/strong&gt ;(spaces added by me)

期望的结果:

This is my <strong>keyword</strong>

【问题讨论】:

    标签: python html beautifulsoup escaping html-escape-characters


    【解决方案1】:

    试试下面的

    from bs4 import BeautifulSoup as soup
    import re
    import html
    
    txt = """<html><head><style></style></head><body><h2>"This is my keyword</h2><table><tr><td>This could be another instance of the keyword.</td></tr></table></body></html>"""
    
    buzz_words = ["keyword", "apples"]
    
    htmlSoup = soup(txt, features="html.parser")
    for word in buzz_words:
        target = htmlSoup.find_all(text=re.compile(r"" + re.escape(word)))
        for v in target:
            v.replace_with(v.replace(word, "".join(["<strong>", word, "</strong>"])))
    print(html.unescape(str(htmlSoup.prettify())))
    

    【讨论】:

    • 这行得通,只是对我的代码稍作调整。非常感谢您的快速帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 2015-05-17
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2012-08-12
    相关资源
    最近更新 更多