artas2357
artas2357

Reputation: 183

How to return tags without attributes in beautiful soup?

For example I have this tag:

<div class="some class name">Some sentence</div>

How can I return it like this:

<div>Some sentence</div>

I want to return it like that for all tags that have attributes, how can I achieve it?

Upvotes: 1

Views: 217

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195543

If you want to clear your HTML document from all attributes, you can use del tag.attrs. For example:

from bs4 import BeautifulSoup

html_doc = """
    <div class="some class name">Some sentence</div>
    <span id="some_id">Some sentence 2</span>
    <div>Some sentence 3</div>
"""

soup = BeautifulSoup(html_doc, "html.parser")

for t in soup.find_all():
    del t.attrs

print(soup)

Prints:


<div>Some sentence</div>
<span>Some sentence 2</span>
<div>Some sentence 3</div>

Upvotes: 2

Rakesh
Rakesh

Reputation: 82785

I believe you need del attribute

Ex:

s = '<div class="some class name">Some sentence</div>'
soup = BeautifulSoup(s, "html.parser")
del soup.div['class']
print(soup.div)  # <div>Some sentence</div>

Upvotes: 1

Related Questions