2012-03-16 5 views
0

2つのHTMLファイルが似ています。それらをold.htmlとnew​​.htmlとしましょう。2つのファイル間の特定のHTMLブロックをPythonに置き換えます。

私はnew.htmlを開き、いくつかの処理を行い、htmlのブロックを保存したいだけです。私はちょうど編集してold.htmlの対応するブロックを置き換えます。

new.htmlがどのように見えるのであれば:

<html> 
<table> 
my content 
</table> 
</html> 

そしてold.htmlは、次のようになります。その後

<html> 
<!--other html --> 
<table> 
old content 
</table> 
<!-- other html --> 

、old.htmlは、次のようになります。

<html> 
<!--other html --> 
<table> 
my content 
</table> 
<!-- other html --> 

I私はこの問題の最初の部分が分かったと思う、私はちょうど実際にファイルを変更する方法を知らない。 私はいくつかのプレースホルダーテキストがうまくいく使用して多分何とかと思ったが、私はまだ私がこれまで持って何old.html

からのコードの元のブロックを交換する方法がわからない:

from bs4 import BeautifulSoup as Soup 
from soupselect import select 

new_file = "\\path\\to\\new.html" 
old_file = "\\path\\to\\old.html" 


f = open(new_file, "rb") 
soup = Soup(f) 
new_table = soup.table 

f2 = open(old_file, "rb") 
soup2 = Soup(f2) 
old_table = soup2.table 

#process new_table here 

#how do i replace old_table with new_table? 
f.close() 
f2.close() 

答えて

0

私のソリューションreqular式を使い、上記の簡単な例のために働きます。しかし、テーブルがたくさんある複雑なHTMLファイルには、より洗練されたソリューションが必要です。

旧HTMLファイル

<html> 
<!--other html --> 
<table> 
replace me 
I'm old and weak 
*cough* can't.. hang.. on.. much... longer.. 
</table> 
<!-- other html --> 

新しいHTMLファイル

<html> 
<table> 
I'm new content 
replace old content with me 
</table> 
</html> 

マイソリューション

import re 

# open the files 
Old = open('/somelocation/old.html').read() 
New = open('/somelocation/new.html').read() 

# get the strings you want to swap 
NewTableContents = re.findall(r'<table>([\s\S]+?)</table>',New)[0] 
OldTableContents = re.findall(r'<table>([\s\S]+?)</table>',Old)[0] 

# replace 
Replace = Old.replace(OldTableContents,NewTableContents) 

# output string to new file 
File = open('/somelocation/oldHTMLWithNewTableContents.html','w') 
File.write(Replace) 
File.close() 

結果のファイル

<html> 
<!--other html --> 
<table> 
I'm new content 
replace old content with me 
</table> 
<!-- other html --> 

この例は、各HTMLファイル内に1つのテーブルがある場合に機能します。ファイルごとに複数のテーブルがある場合は、どのテーブルでどのコンテンツに置き換えたいかによって気になることがあります。

+0

ありがとうございます!ありがたいことに、私が扱っているファイルは、1つのテーブルだけを含むことが保証されているので、これはうまくいきます。私は正規表現の使用を考慮しませんでした。私はいくつかの重労働をするためにBeautifulSoupのような図書館が必要だと思っていました。 – marc

+0

それはあなたのために働いてうれしい。甘い!私の最初に受け入れられた答え! – b10hazard

関連する問題