我想在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)
不幸的是返回
<html><body><p><a href="#replace">replace</a> this string </p></body></html>
我正在寻找:
<html><body><p><a href="#replace">replace</a> this string </p></body></html>
有没有办法告诉BeautifulSoup不要逃避链接元素?
一个简单的正则表达式替换不会在这里做,因为我最终不仅会有一个我想要替换但只有多个的模式.这就是我决定使用BeautifulSoup排除已经是链接的所有内容的原因.
最佳答案 您需要使用
new_tag
创建新标签,使用
insert_after
在新创建的标签后插入部分文本.
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, ""))