How to set value in with Beautiful Soup in some HTML element if I know id of that element or class?

感情迁移 提交于 2021-02-07 11:42:13

问题


How to set value with Beautiful Soup in some element if I know id of that HTML element or class ? For example I have

<td id="test"></td>

and I want to set text RESTORE... like

<td id="test">RESTORE...</td>.


回答1:


Find the tag you want to modify using a find() search for id=test. Then:

BeautifulSoup Documentation - "Modifying the tree"

Modifying .string

If you set a tag’s .string attribute, the tag’s contents are replaced with the string you give:

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)

tag = soup.a
tag.string = "New link text."
tag
# <a href="http://example.com/">New link text.</a>

Be careful: if the tag contained other tags, they and all their contents will be destroyed.



来源:https://stackoverflow.com/questions/9766966/how-to-set-value-in-with-beautiful-soup-in-some-html-element-if-i-know-id-of-tha

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