gpt4 book ai didi

python - 在 BeautifulSoup 中替换文本而不转义

转载 作者:搜寻专家 更新时间:2023-10-31 08:43:48 24 4
gpt4 key购买 nike

我想用 BeautifulSoup 中的 anchor 链接包装一些尚未链接的词。我用这个来实现它:

from bs4 import BeautifulSoup
import re

text = ''' replace this string '''

soup = BeautifulSoup(text)
pattern = 'replace'

for txt in soup.findAll(text=True):
if re.search(pattern,txt,re.I) and txt.parent.name != 'a':
newtext = re.sub(r'(%s)' % pattern,
r'<a href="#\1">\1</a>',
txt)
txt.replaceWith(newtext)
print(soup)

不幸的是返回

<html><body><p>&lt;a href="#replace"&gt;replace&lt;/a&gt; this string </p></body></html>

而我正在寻找:

<html><body><p><a href="#replace">replace</a> this string </p></body></html>

有没有办法告诉 BeautifulSoup 不要转义链接元素?

要替换的简单正则表达式不会在这里执行,因为我最终不仅要替换一个模式,而且要替换多个模式。这就是为什么我决定使用 BeautifulSoup 来排除所有已经是链接的内容。

最佳答案

您需要使用 new_tag 创建新标签使用 insert_after在新创建的 a 标记后插入部分 text

for txt in soup.find_all(text=True):
if re.search(pattern, txt, re.I) and txt.parent.name != 'a':
newtag = soup.new_tag('a')
newtag.attrs['href'] = "#{}".format(pattern)
newtag.string = pattern
txt.replace_with(newtag)
newtag.insert_after(txt.replace(pattern, ""))

关于python - 在 BeautifulSoup 中替换文本而不转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com