Change the text of the inner tag using beautifulsoup python

牧云@^-^@ 提交于 2020-05-14 08:43:53

问题


I would like to change the inner text of a tag in HTML obtained using Beautifulsoup.

Example:

<a href="index.html" id="websiteName">Foo</a>

turns into:

<a href="index.html" id="websiteName">Bar</a>

I have managed to get the tag by it's id by:

HTMLDocument.find(id='websiteName')

But I'm not beeing able to change the inner textof 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

Output:

<a href="index.html" id="websiteName">Foo</a>
<a href="index.html" id="websiteName">Foo</a>

回答1:


Try by changing the string element :

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>


来源:https://stackoverflow.com/questions/47024877/change-the-text-of-the-inner-tag-using-beautifulsoup-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!