BeautifulSoup:如何用元素标签替换元素中的值?

zer*_*lus 9 python beautifulsoup

假设我有这段HT​​ML:

<p>This text is my <a href="#">text</a><p>
Run Code Online (Sandbox Code Playgroud)

如何用锚元素替换第一个"文本",结果变为:

<p>This <a href="#">text</a> is my <a href="#">text</a><p>
Run Code Online (Sandbox Code Playgroud)

我基本上想用一个Tag替换NavigableString中的子字符串.

Leo*_*son 12

你的问题有两个部分:

  1. 将单个NavigableString"This text is my"转换为NavigableString,Tag和另一个NavigableString.

  2. 用三个新元素替换NavigableString"This text is my".

#1的答案取决于你的情况.具体而言,它取决于您如何确定文本的哪个部分需要链接.我将使用正则表达式来查找字符串"text":

from bs4 import BeautifulSoup
data = '<p>This text is my <a href="#">text</a><p>'

soup = BeautifulSoup(data)
original_string = soup.p.contents[0]

print(original_string)
# "This text is my "

import re
this, text, is_my = re.compile("(text)").split(original_string)
Run Code Online (Sandbox Code Playgroud)

现在为#2.这并不像它可能那么容易,但它绝对是可能的.首先,text转入Tag包含链接文本:

text_link = soup.new_tag("a", href="#")
text_link.string = text
Run Code Online (Sandbox Code Playgroud)

re.split()转身thisis_my入寻常Unicode字符串.将它们变回NavigableStrings,以便它们可以作为元素返回树中:

this = soup.new_string(this)
is_my = soup.new_string(is_my)
Run Code Online (Sandbox Code Playgroud)

现在使用replace_with()insert_after用三个新元素替换旧元素:

original_string.replace_with(this)
this.insert_after(text_link)
text_link.insert_after(is_my)
Run Code Online (Sandbox Code Playgroud)

现在你的树应该看起来像你想要的那样:

print(soup.p)
# <p>This <a href="#">text</a> is my <a href=""></a></p>
Run Code Online (Sandbox Code Playgroud)


vvz*_*vzh 5

您可以获取 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))
Run Code Online (Sandbox Code Playgroud)