2012-03-16 86 views
0

我有2個類似的HTML文件,我們稱它們爲old.html和new.html。使用Python替換2個文件之間的特定塊HTML

我想打開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 --> 

我認爲我已經解決了這個問題的第一部分,我只是不知道如何實際修改這些文件。 我想,也許在某種程度上使用一些佔位符文本會的工作,但我還是不知道如何從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

我的解決辦法使用指定的表達式,併爲上面給出的簡單示例工作。但是,一個複雜的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文件中都有一個表,那麼這個例子就可以工作。如果每個文件有多個表,您可能不得不喜歡取決於要替換哪些表的內容。

+0

謝謝!值得慶幸的是,我正在使用的文件將保證只包含一個表格,所以這是正常工作。我沒有考慮使用正則表達式。我想我需要像BeautifulSoup這樣的圖書館來完成一些繁重的工作。 – marc 2012-03-16 18:25:28

+0

很高興爲你工作。甜!我第一個接受的答案! – b10hazard 2012-03-16 18:57:09

相關問題