How do I replace the contents of a HTML document with random text using BeautifulSoup?
<p>Here is code that I've written.</p>

<pre><code>    from bs4 import BeautifulSoup
import urllib
import string, random

def readHtml():
    sock = urllib.urlopen('1041956_Page1.htm')
    soup = BeautifulSoup(sock,'html.parser')
    paraTags = soup.find_all('p')
    for para in paraTags:
        if(para.get_text() is not None):
            para.replace_with(randomizeText(para.get_text())


def randomizeText(text):
    length = len(text)
    newWord = ''.join(random.choice(string.lowercase) for x in range(length-1))
    return newWord

if __name__ == "__main__":
    readHtml()
</code></pre>

<p>This gives me an error that says </p>

<blockquote>
  <p>ValueError: Cannot insert None into a tag.</p>
</blockquote>

<p>I want the  BeautifulSoup object to be replaced with random text would like to rebuild the html from it. Any help would be appreciated. Thanks!</p>

<p>Your <code>randomizeText()</code> isn't returning anything i.e. <code>None</code>. 
Make it:</p>

<pre><code>def randomizeText(text):
    length = len(text)
    newWord = ''.join(random.choice(string.lowercase) for x in range(length))
    print newWord
    return newWord
</code></pre>

<p>and <code>replace_with</code> has a restriction of replacing text with <code>None</code>.</p>

<hr>

<p>Also change the line 10 from:</p>

<pre><code>para.string.replace_with(randomizeText(para.get_text()))
</code></pre>

<p>to </p>

<pre><code>para.replace_with(randomizeText(para.get_text()))
</code></pre>

<p>to avoid the - <strong>AttributeError: 'NoneType' object has no attribute 'replace_with'</strong></p>

<hr>

<p>And my above comment </p>

<blockquote>
  <p>Your code seems to be fine - you may be getting this because of empty
  <code>p</code> block</p>
</blockquote>

<p>is nullified, as i have checked length of empty <code>p</code> block is 1.</p>

python html python-2.7 beautifulsoup