【发布时间】:2018-08-27 13:15:16
【问题描述】:
我找到了要替换的文本,但是当我打印 soup 时,格式发生了变化。 <div id="content">stuff here</div> 变为 &lt;div id="content"&gt;stuff here&lt;/div&gt;。我怎样才能保存数据?我试过print(soup.encode(formatter="none")),但会产生同样的错误格式。
from bs4 import BeautifulSoup
with open(index_file) as fp:
soup = BeautifulSoup(fp,"html.parser")
found = soup.find("div", {"id": "content"})
found.replace_with(data)
当我打印found 时,我得到了正确的格式:
>>> print(found)
<div id="content">stuff</div>
index_file内容如下:
<!DOCTYPE html>
<head>
Apples
</head>
<body>
<div id="page">
This is the Id of the page
<div id="main">
<div id="content">
stuff here
</div>
</div>
footer should go here
</div>
</body>
</html>
【问题讨论】:
-
您的 index_file 以哪种格式保存?你能展示它的一部分吗? (我对 .html 文件和完全相同的代码没有任何问题)
-
文件保存为
.html。如果我打印found一切正常。如果我打印soup,那么我刚刚替换的found将显示&lt;div id="content"&gt;stuff -
是您要执行的确切行吗?因为我尝试在
BeautifulSoup中加载相同的内容,不存在这样的问题。 -
如果不完全相同,则共享完全相同的代码并输出
-
可变数据里面有什么? @user3525290
标签: python python-3.x beautifulsoup