BeautifulSoup - add attribute to tag

The question is for you here, I'm trying to add an attribute to the tag here, wondering if I can use the BeautifulSoup method or use simple string manipulation.

An example is likely to make this clear, as it is a strange explanation.

What the HTML looks like:

<option value="BC">BRITISH COLUMBIA</option> 

How I would like:

 <option selected="" value="BC">BRITISH COLUMBIA</option> 

Thanks for the help!

+6
source share
1 answer

Easy with BeautifulSoup :)

 >>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup('<option value="BC">BRITISH COLUMBIA</option>') >>> soup.find('option')['selected'] = '' >>> print soup <html><body><option selected="" value="BC">BRITISH COLUMBIA</option></body></html> 

Attributes can be seen as a dictionary. So, we have {'value':'BC'} , and to add the value to the dictionary we just do dict[key] = value

+16
source

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


All Articles