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>Simply set the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string" rel="nofollow"><code>.string</code> property</a>:</p>

<pre><code>from bs4 import BeautifulSoup

data = """
 &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;
"""

soup = BeautifulSoup(data, "html.parser")
frame = soup.iframe

frame.string = 'this is the replacement'

print(soup.prettify())
</code></pre>

<p>Prints:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
 &lt;body&gt;
  &lt;iframe src="http://www.w3schools.com"&gt;
   this is the replacement
  &lt;/iframe&gt;
 &lt;/body&gt;
&lt;/html&gt;
</code></pre>

python iframe beautifulsoup