How to set value using Beautiful Soup in any HTML element if I know the id of this element or class?

How to set a value using Beautiful Soup in any element if I know the identifier of this HTML element or class? For example, I have

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

and I want to set the text to RESTORE ... as

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

+6
source share
1 answer

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

BeautifulSoup Documentation - "Modifying a Tree"

Change .string

If you set the .string tag attribute, the contents of the tags are replaced with the line 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 contains other tags, they and all their contents will be destroyed.

+11
source

Source: https://habr.com/ru/post/911071/


All Articles