find() after replaceWith() doesn't work (using BeautifulSoup)

beautifulsoup, find, python

Solution

Simpler answer : after your call to `replaceWith`, regenerate and clean `s` by calling `s = BeautifulSoup(s.renderContents())`. Then you can `find` again.

Problem

Please consider the following python session: ``` >>> from BeautifulSoup import BeautifulSoup >>> s = BeautifulSoup("<p>This <i>is</i> a <i>test</i>.</p>"); myi = s.find("i") >>> myi.replaceWith(BeautifulSoup("was")) >>> s.find("i") >>> s = BeautifulSoup("<p>This <i>is</i> a <i>test</i>.</p>"); myi = s.find("i") >>> myi.replaceWith("was") >>> s.find("i") <i>test</i> ``` Please note the missing output of s.find("i") after line 4! What's the reason for this? Is there a workaround? EDIT: Actually, the example doesn't demonstrate the usecase, which is: ``` myi.replaceWith(BeautifulSoup("wa<b>s</b>")) ``` Whenever the inserted part contains itself nontrivial html code, I don't see how you could replace this syntax with something else. Just having ``` myi.replaceWith("wa<b>s</b>") ``` will replace the html special chars by entities.

Original source