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>
Asked: 2022-10-05 11:00:00 +0000
Seen: 8 times
Last updated: Oct 12 '21