0

Here is my code:

#Manipulating HTML and saving changed with BeautifulSoup



#Importing libraries
from bs4 import BeautifulSoup

#Opening the local HTML file
site_html = open(r"C:\Users\rbaden\desktop\KPI_Site\index.html")


#Creating Soup from source HTML file
soup =BeautifulSoup(site_html)
#print(soup.prettify())


#Locate and view specified class in HTML file
test = soup.find_all(class_='test-message-one')
print(test)


#Test place holder for a python variable that should replace the specified class
var = ('Testing...456')


#Replace the class in soup redition of HTML
for i in soup.find_all(class_='test-message-one'):
    i.string = var


#overwriting the source HTML file on local drive
with open(r"C:\Users\rbaden\desktop\KPI_Site\index.html")
    f.write(soup.content)

This is the error:

enter image description here

How do I correctly overwrite the entire source file with a new file after the changes made with beautifulsoup?

ruben_KAI
  • 325
  • 6
  • 18

1 Answers1

0

You're using wrong syntax for that. The correct one is

with open(file, mode) as variable:
   # do something with variable

In your case it would be

with open(r"C:\Users\rbaden\desktop\KPI_Site\index.html","w") as f:
    #  I forgot 'mode' argument to open                ^^^^^^^^
    #f.write(...)

See this StackOverflow answer for more information.

The complete syntax:

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

See the docs.

Edit: you're opening the file wrongly too. See the edits.

Community
  • 1
  • 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98