在BeautifulSoup中用<tag> substring </tag>替换子字符串

问题描述


我正在尝试修改现有的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>

解决方法

尝试以下

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...