如果我知道某个HTML元素或类的id,如何使用beautifuldsoup在其中设置值?

2024-09-27 09:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我知道HTML元素或类的id,如何在某个元素中使用beautifuldsoup设置值? 例如我有

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

我想设置文本还原。。。就像

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


Tags: test文本gtid元素htmlrestoretd
1条回答
网友
1楼 · 发布于 2024-09-27 09:24:04

使用find()搜索id=test查找要修改的标记。然后:

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.

相关问题 更多 >

    热门问题