如果我知道某个元素或类的ID,如何在某个HTML元素中的Beautiful Soup中设置值?
问题描述:
如果我知道某个HTML元素或类的ID,如何在某些元素中用Beautiful Soup设置值?例如我有
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>
.
答
使用 find()
搜索 id = test
查找要修改的标签.然后:
Find the tag you want to modify using a find()
search for id=test
. Then:
修改.string
如果您设置标签的.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.