Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 399
Kelan Poten-Coyle Avatar asked Jul 05 '13 22:07

Kelan Poten-Coyle


People also ask

Is tag editable in BeautifulSoup?

The navigablestring object is used to represent the contents of a tag. To access the contents, use “. string” with tag. You can replace the string with another string but you can't edit the existing string.

How do you make a tag on BeautifulSoup?

A new tag can be created by calling BeautifulSoup's inbuilt function new_tag(). Inserting a new tag using the append() method : The new tag is appended to the end of the parent tag.

How do you edit HTML with BeautifulSoup?

Step 1: First, import the libraries Beautiful Soup, os and re. Step 2: Now, remove the last segment of the path. Step 3: Then, open the HTML file in which you wish to make a change. Step 4: Moreover, parse the HTML file in Beautiful Soup.

How do you get attributes in BeautifulSoup?

To extract attributes of elements in Beautiful Soup, use the [~] notation. For instance, el["id"] retrieves the value of the id attribute.


1 Answers

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

like image 107
TerryA Avatar answered Oct 17 '22 23:10

TerryA