Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 修改 HTML

2025年05月04日27pengyingh

我想使用 Beautifulsoup 修改 HTML 的整个 div。我试图修改 HTML,但是控制台输出有修改,但实际的 .html 文档本身没有修改。没有创建新的 HTML。

有人可以帮助我吗?

from bs4 import BeautifulSoup,Tag 
import re 
import urllib2 
import os.path 
base=os.path.dirname(os.path.abspath(__file__)) 
 
html=open(os.path.join(base,'example.html')) 
soup=BeautifulSoup(html,'html.parser') 
 
 
for i in  soup.find('div',{"id":None}).findChildren(): 
    l=str(i); 
    print l 
    print l.replace(l,'##') 

请您参考如下方法:

两件事:

  1. 您需要添加一些代码以将 BeautifulSoup 的输出写回文件。
  2. 你应该使用replace_with()对 HTML 进行更改。通过转换为字符串,您只是在修改文本副本。

这可以按如下方式完成:

from bs4 import BeautifulSoup 
import os 
 
base = os.path.dirname(os.path.abspath(__file__)) 
html = open(os.path.join(base, 'example.html')) 
soup = BeautifulSoup(html, 'html.parser') 
 
for i in soup.find('div', {"id":None}).findChildren(): 
    i.replace_with('##') 
 
with open("example_modified.html", "wb") as f_output: 
    f_output.write(soup.prettify("utf-8"))