I'm currently using BeautifulSoup4 with Python 2.7 and trying to instantiate a new tag, with a certain class
attribute. I know how to use attributes such as style
:
div = soup.new_tag('div', style='padding-left: 10px', attr2='...', ...)
However, if I try to do this with the class
reserved word, I get an error (invalid syntax).
div = soup.new_tag('div', class='left_padded', attr2='...', ...) # Throws error
I have also tried with 'class'='...'
, but this is also invalid. I can use Class='...'
, but then the output is not properly compliant (all lowercase attribute names).
I am aware that I can do the following:
div = soup.new_tag('div', attr2='...', ...)
div['class'] = 'left_padded'
But this does not look elegant or intuitive. My research in the docs and on Google were fruitless, as "class" is a common keyword that is unrelated to the search results I want.
Is there a way I can specify class
as an attribute in new_tag()
?
To define a class attribute, you place it outside of the __init__() method. Use class_name. class_attribute or object_name. class_attribute to access the value of the class_attribute .
But be careful, if you want to change a class attribute, you have to do it with the notation ClassName. AttributeName. Otherwise, you will create a new instance variable.
while you can access class attributes using an instance it's not safe to do so. In python, the instance of a class is referred to by the keyword self. Using this keyword you can access not only all instance attributes but also the class attributes.
Definition and Usage The class attribute specifies one or more classnames for an element. The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.
Here is one option:
>>> attributes = {'class': 'left_padded', 'attr2': '...'}
>>> div = soup.new_tag('div', **attributes)
>>> div
<div attr2="..." class="left_padded"></div>
This unpacks the attributes
dictionary into keyword arguments using the **
operator, corresponding to **attrs
in the function signature of soup.new_tag()
. I don't think this is any more elegant than your solution using div['class']
, though.
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