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

标签 python beautifulsoup

我想更改使用 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/

相关文章:

python - 如何使用 BeautifulSoup bs4 获取 HTML 标签的内部文本值?

python - 一个 for 循环中的多个 findAll

python - 我可以使用 BeautifulSoup 删除脚本标签吗?

Python比较两个字符串

python - 在 PyQt 中启动 new QThread() 时传递参数

python - 从 __init__ 中删除工作以帮助单元测试

python - BeautifulSoup-Python : How do you scrape data that has not been loaded yet?

python - 如何在 BeautifulSoup 中呈现 unicode 标签的内容?

python - Tornado 中的队列和 ProcessPoolExecutor

python - 如果没有图像处理Python库(Pillow和cv2)无法读取,如何解码这个二进制图像文件?