2010-03-03 186 views
0

我想使它所以這個腳本如何將輸出保存爲python腳本的文本文件?

from BeautifulSoup import BeautifulSoup 
import sys, re, urllib2 
import codecs 

html_str = urllib2.urlopen(URL).read() 

soup = BeautifulSoup(html_str) 

for row in soup.findAll("tr"): 
    for col in row.findAll(re.compile("td|th")): 
    for 
    sys.stdout.write((col.string if col.string else '') + '|') 
    print # Newline 

將其輸出到一個文本文件來代替。

回答

4

最簡單嗎? (如果* nix中): -

python file.py > filename.txt 

代碼雖然明智: -

from BeautifulSoup import BeautifulSoup 
import sys, re, urllib2 
import codecs 

html_str = urllib2.urlopen(URL).read() 

soup = BeautifulSoup(html_str) 

file = open('file.txt', 'w') 

for row in soup.findAll("tr"): 
    for col in row.findAll(re.compile("td|th")): 
    file.write((col.string if col.string else '') + '|') 

file.close() 
+0

最簡單的方法在Windows上運行過 – mattmanser 2011-07-12 09:52:16

相關問題