使用BeautifulSoup修改HTML [英] Using BeautifulSoup to modify HTML

查看:626
本文介绍了使用BeautifulSoup修改HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use Beautifulsoup to modify a whole div of a HTML. I was trying to modify the HTML, however the console output has the modifications, but the actual .html document itself is not modified. No new HTML was created.

有人可以帮助我吗?

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"))  

这篇关于使用BeautifulSoup修改HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆