[英]Error writing over source HTML file after BeautifulSoup edit
这是我的代码:
#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(...)
有关更多信息,请参见此StackOverflow答案 。
完整语法:
with_stmt ::= "with" with_item ("," with_item)* ":" suite
with_item ::= expression ["as" target]
请参阅文档 。
编辑 :您也错误地打开了文件。 查看修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.