Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify a class attribute in new_tag()?

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()?

like image 294
Cat Avatar asked Jan 12 '14 03:01

Cat


People also ask

How do you declare a class attribute in Python?

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 .

How do you modify a class attribute in Python?

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.

Can a class attribute be used without instance?

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.

What is a class attribute?

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.


1 Answers

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.

like image 197
senshin Avatar answered Sep 28 '22 00:09

senshin