Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 美化组编辑后在源HTML文件上写入时出错_Python_Html_Windows_Beautifulsoup - Fatal编程技术网

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,您错误地打开了文件。请看编辑