Ask Your Question
2

How can a class be assigned as an attribute in a new tag using python beautifulsoup?

asked 2022-10-05 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-12 21:00:00 +0000

ladyg gravatar image

To assign a class as an attribute in a new tag using Python BeautifulSoup, you can use the new_tag() method to create the tag and then use the attrs parameter to add the class attribute.

Here's an example:

from bs4 import BeautifulSoup

html = '<html><body><div>Hello</div></body></html>'
soup = BeautifulSoup(html, 'html.parser')

new_div = soup.new_tag('div', attrs={'class': 'new-class'})

soup.body.append(new_div)

print(soup.prettify())

In this example, a new div tag is created using the new_tag() method and the attrs parameter is used to add the class attribute with the value of new-class. The new div tag is then added to the body tag using the append() method.

The output of this code will be:

<html>
 <body>
  <div>
   Hello
  </div>
  <div class="new-class">
  </div>
 </body>
</html>
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-05 11:00:00 +0000

Seen: 8 times

Last updated: Oct 12 '21