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>
.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With