【问题标题】:Using BeautifulSoup to modify HTML使用 BeautifulSoup 修改 HTML
【发布时间】:2016-11-23 23:39:37
【问题描述】:

我想使用 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,'##')

【问题讨论】:

  • 您是否尝试保存文件? from __future__ import print_function print("hi there", file=f)

标签: python html beautifulsoup


【解决方案1】:

两件事:

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

【讨论】:

  • bs4 中的element.py 模块说DEFAULT_OUTPUT_ENCODING = "utf-8",所以我认为你可以省略"utf-8"。但这是 2020 年,所以自 2016 年以来情况可能发生了很大变化。
猜你喜欢
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 2020-01-16
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多