使用beautifulsoup python更改内部标签的文本

Cha*_*lie 3 python beautifulsoup

我想更改inner text使用Beautifulsoup.

例子:

<a href="index.html" id="websiteName">Foo</a>
Run Code Online (Sandbox Code Playgroud)

变成:

<a href="index.html" id="websiteName">Bar</a>
Run Code Online (Sandbox Code Playgroud)

我已经设法通过它的 id 获得了标签:

HTMLDocument.find(id='websiteName')
Run Code Online (Sandbox Code Playgroud)

但我无法更改inner text标签的:

print HTMLDocument.find(id='websiteName')

a = HTMLDocument.find(id='websiteName')
a = a.replaceWith('<a href="index.html" id="websiteName">Bar</a>')

// I have tried using this as well
a = a.replaceWith('Bar')

print a
Run Code Online (Sandbox Code Playgroud)

输出:

<a href="index.html" id="websiteName">Foo</a>
<a href="index.html" id="websiteName">Foo</a>
Run Code Online (Sandbox Code Playgroud)

PRM*_*reu 12

尝试更改字符串元素:

HTMLDocument.find(id='websiteName').string.replace_with('Bar')
Run Code Online (Sandbox Code Playgroud)
from bs4 import BeautifulSoup as soup

html = """
<a href="index.html" id="websiteName">Foo</a>
"""
soup = soup(html, 'lxml')
result = soup.find(id='websiteName')

print(result)
# >>> <a href="index.html" id="websiteName">Foo</a>

result.string.replace_with('Bar')
print(result)
# >>> <a href="index.html" id="websiteName">Bar</a>
Run Code Online (Sandbox Code Playgroud)