我想更改使用 Beautifulsoup
获得的 HTML 标签的 inner text
。
例子:
<a href="index.html" id="websiteName">Foo</a>
变成:
<a href="index.html" id="websiteName">Bar</a>
我已经设法通过它的 id 获取标签:
HTMLDocument.find(id='websiteName')
但我无法更改标签的内部文本
:
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
输出:
<a href="index.html" id="websiteName">Foo</a>
<a href="index.html" id="websiteName">Foo</a>
最佳答案
尝试改变字符串元素:
HTMLDocument.find(id='websiteName').string.replace_with('Bar')
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>
关于python - 使用 beautifulsoup python 更改内部标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47024877/