这是我的代码:
#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)
这是错误:
使用beautifulsoup进行更改后,如何使用新文件正确覆盖整个源文件?
答案 0 :(得分:0)
你使用了错误的语法。正确的是
with open(file, mode) as variable:
# do something with variable
在你的情况下,它将是
with open(r"C:\Users\rbaden\desktop\KPI_Site\index.html","w") as f:
# I forgot 'mode' argument to open ^^^^^^^^
#f.write(...)
有关详细信息,请参阅this StackOverflow answer。
完整语法:
with_stmt ::= "with" with_item ("," with_item)* ":" suite
with_item ::= expression ["as" target]
请参阅the docs。
修改:您也错误地打开了文件。请参阅编辑。