Change string Beautiful Soup
Question: I have a problem writing code in Python and BS4.

Assuming have the next paragraph:

    
    
    <p id="paragraph">
    Here is the paragraph <a href="/" id="url">Here an url</a> the paragraph continues.
    </p>
    

I take the id and use `replace_with` to replace the string (in P and A tag).
But in this case, results in this:

    
    
    Here is the paragraph the paragraph continues. Here an url
    

The structure is not respected. What is the correct method?

Add some code:

    
    
    page = open('file.html')
    soupPage = BeautifulSoup(page)
    findId = soupPage.find(id='nameOfId')
    findId.replace_with('NewString')
    


Answer: Try this:

    
    
    from bs4 import BeautifulSoup
    
    page = open('file.html')
    soupPage = BeautifulSoup(page)
    findId = soupPage.find(id='url')
    findId.contents[0].replace_with('NewString')
    print soupPage
    

prints:

    
    
    <html><body><p id="paragraph">
    Here is the paragraph <a href="/" id="url">NewString</a> the paragraph continues.
    </p></body></html>
    

Hope it's what you wanted.

