Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>.

like image 413
Damir Avatar asked Mar 19 '12 08:03

Damir


People also ask

How do you get a href value in BeautifulSoup?

To get href with Python BeautifulSoup, we can use the find_all method. to create soup object with BeautifulSoup class called with the html string. Then we find the a elements with the href attribute returned by calling find_all with 'a' and href set to True .


1 Answers

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.

like image 142
Li-aung Yip Avatar answered Oct 10 '22 21:10

Li-aung Yip