2016-11-23 5 views
-1

Beautifulsoupを使用して、HTMLのdiv全体を修正します。私はHTMLを修正しようとしていましたが、コンソール出力に変更がありましたが、実際の.htmlドキュメント自体は変更されていません。新しいHTMLは作成されませんでした。BeautifulSoupを使用して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,'##') 
+0

あなたは、ファイルを保存しようとしましたか? 'from __future__ import print_function print(" hi there "、file = f)' – paragbaxi

答えて

0

2つのこと:

  1. あなたが戻ってファイルにBeautifulSoupからの出力を書き込むためのいくつかのコードを追加する必要があります。
  2. 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")) 
関連する問題