mic*_*lle 1 html python beautifulsoup
我想使用Beautifulsoup修改整个divHTML。我试图修改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,'##')
Run Code Online (Sandbox Code Playgroud)
两件事情:
replace_with()用来对HTML进行更改。通过转换为字符串,您只是在修改文本副本。可以按照以下步骤进行:
from bs4 import BeautifulSoup
import urllib2
import re
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"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2910 次 |
| 最近记录: |