How to use BeautifulSoup to replace a tag with its contents?

How to use BeautifulSoup to remove only a tag? The method I found removes the tag and all other tags and content inside it. I want to remove only the tag and leave everything inside it untouched, for example.

change this:

<div> <p>dvgbkfbnfd</p> <div> <span>dsvdfvd</span> </div> <p>fvjdfnvjundf</p> </div> 

:

 <p>dvgbkfbnfd</p> <span>dsvdfvd</span> <p>fvjdfnvjundf</p> 
+4
source share
1 answer

I voted to close it as a duplicate, but if you use it, reusing the slice answer from the top answer on the right will get this solution:

 from BeautifulSoup import BeautifulSoup html = ''' <div> <p>dvgbkfbnfd</p> <div> <span>dsvdfvd</span> </div> <p>fvjdfnvjundf</p> </div> ''' soup = BeautifulSoup(html) for match in soup.findAll('div'): match.replaceWithChildren() print soup 

... which produces the result:

 <p>dvgbkfbnfd</p> <span>dsvdfvd</span> <p>fvjdfnvjundf</p> 
+3
source

Source: https://habr.com/ru/post/1412046/


All Articles