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!
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.
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.
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.
To extract attributes of elements in Beautiful Soup, use the [~] notation. For instance, el["id"] retrieves the value of the id attribute.
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
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