Python 美化组编辑后在源HTML文件上写入时出错
这是我的密码:Python 美化组编辑后在源HTML文件上写入时出错,python,html,windows,beautifulsoup,Python,Html,Windows,Beautifulsoup,这是我的密码: #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 fi
#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进行更改后,如何正确地用新文件覆盖整个源文件?您使用了错误的语法。正确的答案是
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(...)
有关更多信息,请参阅
完整语法:
with_stmt ::= "with" with_item ("," with_item)* ":" suite
with_item ::= expression ["as" target]
看
编辑:您也错误地打开了文件。请参阅编辑。使用“as f”我得到以下类型错误:必须是str,而不是None@RubenBaden,您错误地打开了文件。请看编辑