将 Beautifulsoup 写回原始 HTML 文件时出错
Error while writing Beautifulsoup back over original HTML file
我的原始 HTML 文件的 BeautifulSoup 副本的编码可能有问题吗?
我被告知我无法写入文件,因为我必须写一个 str 而不是 none。
请参阅下面的代码和 TypeError
:
#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") as f:
f.write(soup.content)
首先,您需要以w
模式打开文件。
而且,您需要写 str(soup)
或 soup.prettify()
:
with open(r"C:\Users\rbaden\desktop\KPI_Site\index.html", "w") as f:
f.write(soup.prettify())
我的原始 HTML 文件的 BeautifulSoup 副本的编码可能有问题吗?
我被告知我无法写入文件,因为我必须写一个 str 而不是 none。
请参阅下面的代码和 TypeError
:
#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") as f:
f.write(soup.content)
首先,您需要以w
模式打开文件。
而且,您需要写 str(soup)
或 soup.prettify()
:
with open(r"C:\Users\rbaden\desktop\KPI_Site\index.html", "w") as f:
f.write(soup.prettify())