Python BeautifulSoup:如何用元素标记替换元素中的值?
假设我有一段HTML:Python BeautifulSoup:如何用元素标记替换元素中的值?,python,beautifulsoup,Python,Beautifulsoup,假设我有一段HTML: <p>This text is my <a href="#">text</a><p> 此文本是我的 如何将第一个“文本”替换为锚元素,使结果变为: <p>This <a href="#">text</a> is my <a href="#">text</a><p> 这是我的 我基本上想用标记替换NavigableString中的子字符串。您的问题
<p>This text is my <a href="#">text</a><p>
此文本是我的
如何将第一个“文本”替换为锚元素,使结果变为:
<p>This <a href="#">text</a> is my <a href="#">text</a><p>
这是我的
我基本上想用标记替换NavigableString中的子字符串。您的问题有两部分:
re.split()。将它们返回到navigablesting
s,以便它们可以作为元素返回到树中:
this = soup.new_string(this)
is_my = soup.new_string(is_my)
original_string.replace_with(this)
this.insert_after(text_link)
text_link.insert_after(is_my)
现在使用replace_with()
和insert_after
将旧元素替换为三个新元素:
this = soup.new_string(this)
is_my = soup.new_string(is_my)
original_string.replace_with(this)
this.insert_after(text_link)
text_link.insert_after(is_my)
现在,您的树应该按照您希望的方式显示:
print(soup.p)
# <p>This <a href="#">text</a> is my <a href=""></a></p>
打印(soup.p)
#这是我的
您可以获取NavigableString的文本,对其进行修改,根据修改后的文本构建新的对象模型,然后使用此对象模型替换旧的NavigableString:
data = '<p>This text is my <a href="#">text</a><p>'
soup = BeautifulSoup(data)
original_string = soup.p.contents[0]
new_text = unicode(original_string).replace('text', '<a href="#">text</a>')
original_string.replaceWith(BeautifulSoup(text))
data='此文本是我的'
汤=美汤(数据)
原始字符串=soup.p.contents[0]
新文本=unicode(原始字符串)。替换('text','')
原始字符串。替换为(美化组(文本))