Add content to iframe with BeautifulSoup
<p>Let say I have the following iframe</p>

<pre><code> s=""""
 &lt;!DOCTYPE html&gt;
 &lt;html&gt;
 &lt;body&gt;

 &lt;iframe src="http://www.w3schools.com"&gt;         
   &lt;p&gt;Your browser does not support iframes.&lt;/p&gt;
 &lt;/iframe&gt;

 &lt;/body&gt;
 &lt;/html&gt;
 """
</code></pre>

<p>I want to replace all content with this string 'this is the replacement'
If I use</p>

<pre><code>dom = BeatifulSoup(s, 'html.parser')
f = dom.find('iframe')
f.contents[0].replace_with('this is the replacement')
</code></pre>

<p>Then instead of replacing all the content I will replace only the first character, which in this case is a newline. Also this does not work if the iframe is completely empty because f.contents[0] is out of index</p>

<p>This will work for you to replace the <code>iframe</code> tag content.</p>

<pre><code>s="""
 &lt;!DOCTYPE html&gt;
 &lt;html&gt;
 &lt;body&gt;
 &lt;iframe src="http://www.w3schools.com"&gt;
   &lt;p&gt;Your browser does not support iframes.&lt;/p&gt;
 &lt;/iframe&gt;
 &lt;/body&gt;
 &lt;/html&gt;
 """
from BeautifulSoup import BeautifulSoup
from HTMLParser import HTMLParser

soup = BeautifulSoup(s, convertEntities=BeautifulSoup.HTML_ENTITIES)
show= soup.findAll('iframe')[0]
show.replaceWith('&lt;iframe src="http://www.w3schools.com"&gt;this is the replacement&lt;/iframe&gt;'.encode('utf-8'))
html = HTMLParser()
print html.unescape(str(soup.prettify()))
</code></pre>

<p>Output:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
 &lt;body&gt;
  &lt;iframe src="http://www.w3schools.com"&gt;my text&lt;/iframe&gt;
 &lt;/body&gt;
&lt;/html&gt;
</code></pre>

python iframe beautifulsoup