Kelan Poten-Coyle
Kelan Poten-Coyle

Reputation: 305

BeautifulSoup - adding attribute to tag

Question for you here, I'm trying to add an attribute to a tag here, wondering if I can use a BeautifulSoup method, or should use plain string manipulation.

An example would probably make this clear, as it's a weird explanation.

How the HTML Code looks now:

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

How I would like it to look:

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

Thanks for the help!

Upvotes: 24

Views: 22038

Answers (1)

TerryA
TerryA

Reputation: 59974

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>

The attributes can be looked at as a dictionary. So we have {'value':'BC'}, and to add a value to a dictionary, we just do dict[key] = value

Upvotes: 38

Related Questions