@杰克转瞬
在下面的示例中,我想将“Início”替换为“Start”:
原文:
<li class="current"><a style="color:#00233C;" href="index.html"><i class="icon icon-home"></i> Início</a></li>
预期结果:
<li class="current"><a style="color:#00233C;" href="index.html"><i class="icon icon-home"></i> Start</a></li>
字典中的一个例子:
dict = {
"Início": "Start",
"Ajuda": "Help",
"Criar Alerta": "Create Alert",
"Materiais e Estruturas": "Structures and Materials"
...
}
以下是我编写的代码,用于练习使用 BeautifulSoup 进行 HTML 解析。
(我注意到所有要替换的字符串都在“a”标签内,然后我使用了SoupStrainer(“a”))
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
with open(html_file, 'rb') as src:
doc = src.read()
src.close()
only_a_tags = SoupStrainer("a")
parse_1 = 'html.parser'
soup = BeautifulSoup(doc, parse_1, parse_only=only_a_tags)
print(soup.prettify())
原行解析打印如下:
<a href="index.html" style="color:#00233C;">
<i class="icon icon-home">
</i>
Início
</a>
鉴于上面的打印,我不确定是否能够获得预期的结果。
我的目的是找到每一行的字符串,然后在字典中搜索它的等价物,然后执行替换。
现在,我想知道如何使用 BeatifulSoup 执行这种字符串替换。
之后,我将编写一个“for”循环,最终对 HTML 文件中的所有行进行替换。
我的第一次尝试(在了解 BeautifulSoup 之前)是处理以二进制形式读取的 HTML 文件的 .txt 版本,这证明自己非常耗时且效率低下。