k-n*_*nut 5 html python escaping beautifulsoup
我想用 BeautifulSoup 中的锚链接包装一些尚未链接的单词。我用它来实现它:
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)
Run Code Online (Sandbox Code Playgroud)
不幸返回
<html><body><p><a href="#replace">replace</a> this string </p></body></html>
Run Code Online (Sandbox Code Playgroud)
而我正在寻找:
<html><body><p><a href="#replace">replace</a> this string </p></body></html>
Run Code Online (Sandbox Code Playgroud)
有没有办法告诉 BeautifulSoup 不要逃避链接元素?
要替换的简单正则表达式在这里不起作用,因为我最终不仅要替换一个模式,而且要替换多个模式。这就是为什么我决定使用 BeautifulSoup 来排除已经是链接的所有内容。
您需要使用new_taguse创建新标签,在新创建的标签后insert_after插入部分内容。texta
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, ""))
Run Code Online (Sandbox Code Playgroud)