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

查看:65
本文介绍了使用 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 进行更改.通过转换为字符串,您只是在修改文本副本.

这可以按如下方式完成:

This can be done as follows:

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天全站免登陆