我想用 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 http://www.crummy.com/software/BeautifulSoup/bs4/doc/#beautifulsoup-new-string-and-new-tag use insert_after http://www.crummy.com/software/BeautifulSoup/bs4/doc/#insert-before-and-insert-after插入您的一部分text
在你新创建之后a
tag.
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, ""))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)