Search code examples
pythonhtmltagsattributesbeautifulsoup

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!


Solution

  • 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