使用beautifulsoup python更改内部标签的文本 [英] Change the text of the inner tag using beautifulsoup python
本文介绍了使用beautifulsoup python更改内部标签的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更改使用Beautifulsoup
获得的HTML中的标记的inner text
.
I would like to change the inner text
of a tag in HTML obtained using Beautifulsoup
.
示例:
<a href="index.html" id="websiteName">Foo</a>
变成:
<a href="index.html" id="websiteName">Bar</a>
我设法通过它的id来获取标签:
I have managed to get the tag by it's id by:
HTMLDocument.find(id='websiteName')
但是我无法更改标签的inner text
:
But I'm not beeing able to change the inner text
of the tag:
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>
这篇关于使用beautifulsoup python更改内部标签的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文