How to specify a class attribute in new_tag ()?

I am currently using BeautifulSoup4 with Python 2.7 and am trying to instantiate a new tag with a specific class attribute. I know how to use attributes like style :

 div = soup.new_tag('div', style='padding-left: 10px', attr2='...', ...) 

However, if I try to do this with the reserved word class , I get an error message (invalid syntax).

 div = soup.new_tag('div', class='left_padded', attr2='...', ...) # Throws error 

I also tried with 'class'='...' , but this is also not true. I can use Class='...' , but then the result does not meet the requirements (all lowercase names).

I know I can do the following:

 div = soup.new_tag('div', attr2='...', ...) div['class'] = 'left_padded' 

But it does not look elegant or intuitive. My research in documents and on Google was fruitless, since β€œclass” is a common keyword that is not related to the search results I want.

Is it possible to specify class as an attribute in new_tag() ?

+6
source share
1 answer

Here is one of the options:

 >>> attributes = {'class': 'left_padded', 'attr2': '...'} >>> div = soup.new_tag('div', **attributes) >>> div <div attr2="..." class="left_padded"></div> 

This decompresses the attributes dictionary into keyword arguments using the ** operator corresponding to **attrs in the signature of soup.new_tag() . I do not think this is more elegant than your solution using div['class'] .

+5
source

All Articles