0
>>> from bs4 import BeautifulSoup
>>> sample = '''\
... <section id="about" class="about-section">
...     <div class="container">
...         <div class="row">
...             <div class="col-lg-12">
...                 <h1>About Section</h1>
... 
...                 <p class = "test-message-one"> Hey </p>
... 
...             </div>
...         </div>
...     </div>
... </section>
... '''
>>> soup = BeautifulSoup(sample)
>>> test = soup.find_all(class_='test-message-one')
>>> print(test)

returns

[<p class="test-message-one"> Hey </p>]

How do I replace the contents 'Hey' with a string saved in python?

I need the HTML to be overwritten with a varibale that I have saved - but most of the documenation I understand in BS4 only shows how to change the name of the class - not the content itself.

Lets say I have this string in python:

>>> replace=('Testing...123')

How do I get it to write back over the HTML to this:

  >>> from bs4 import BeautifulSoup
    >>> sample = '''\
    ... <section id="about" class="about-section">
    ...     <div class="container">
    ...         <div class="row">
    ...             <div class="col-lg-12">
    ...                 <h1>About Section</h1>
    ... 
    ...                 <p class = "test-message-one"> Testing...123 </p>
    ... 
    ...             </div>
    ...         </div>
    ...     </div>
    ... </section>
    ... '''

1 Answer 1

2

You could do like this,

for i in soup.find_all(class_='test-message-one'):
    i.string = var
print soup

where var is the variable which stores the replacement string.

Sign up to request clarification or add additional context in comments.

3 Comments

This is great! Worked perfectly - But I think it only saved the change in the soup! How do I actually overwrite the HTML file with the new soup so it updates my HTML page?
just write the contents of soup variable to another file. A simple google search will give the results.
Great! Thanks - your wisdom is much appreciated, I am new to Python and BS4, but they are exciting tools!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.