python - 在原始 HTML 文件上写回 Beautifulsoup 时出错

标签 python html windows beautifulsoup html-parsing

我的原始 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)

enter image description here

最佳答案

首先,您需要以w 模式打开文件。

并且,您需要编写 str(soup)soup.prettify():

with open(r"C:\Users\rbaden\desktop\KPI_Site\index.html", "w") as f:
    f.write(soup.prettify())

关于python - 在原始 HTML 文件上写回 Beautifulsoup 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29263372/

相关文章:

java - 是否有任何可以与 PHP/Python/其他集成的沙盒脚本引擎?

javascript - 是否可以在没有服务器往返的情况下更新地址栏?

c++ - Visual Studio中的 "win32 project"名称与x86或x64平台有什么关系

python - Apache Tika 排除了一些 html 标签

python - 如何为/: 'str' and 'int' in for loops处理不受支持的操作数类型

python - 在mysql中将项目推送到堆栈的末尾

php - 如何将 mysql 'id' 链接到 html 元素

CSS:隐藏的 html 标签显示后位置中断

windows - 将文件从 Ubuntu 远程复制到 Windows 7

windows - 带有通配符的 Robocopy 批处理复制的文件多于应有的数量。为什么?