http://www.srh.noaa.gov/data/obhistory/PAFA.htmlの NOAA データから csv ファイルを作成しようとしています。
table タグを操作しようとしましたが、失敗しました。だから私は<tr>
各行で識別してそれをやろうとしています。これは私のコードです:
#This script should take table context from URL and save new data into a CSV file.
noaa = urllib2.urlopen("http://www.srh.noaa.gov/data/obhistory/PAFA.html").read()
soup = BeautifulSoup(noaa)
#Iterate from lines 7 to 78 and extract the text in each line. I probably would like
#space delimited between each text
#for i in range(7, 78, 1):
rows = soup.findAll('tr')[i]
for tr in rows:
for n in range(0, 15, 1):
cols = rows.findAll('td')[n]
for td in cols[n]:
print td.find(text=true)....(match.group(0), match.group(2), match.group(3), ...
match.group(15)
現時点では、期待どおりに機能しているものもあれば、機能していないものもあり、最後の部分は、希望どおりにステッチする方法がわかりません.
わかりましたので、「That1guy」が提案したものを取り、それを CSV コンポーネントに拡張しようとしました。そう:
import urllib2 as urllib
from bs4 import BeautifulSoup
from time import localtime, strftime
import csv
url = 'http://www.srh.noaa.gov/data/obhistory/PAFA.html'
file_pointer = urllib.urlopen(url)
soup = BeautifulSoup(file_pointer)
table = soup('table')[3]
table_rows = table.findAll('tr')
row_count = 0
for table_row in table_rows:
row_count += 1
if row_count < 4:
continue
date = table_row('td')[0].contents[0]
time = table_row('td')[1].contents[0]
wind = table_row('td')[2].contents[0]
print date, time, wind
with open("/home/eyalak/Documents/weather/weather.csv", "wb") as f:
writer = csv.writer(f)
print date, time, wind
writer.writerow( ('Title 1', 'Title 2', 'Title 3') )
writer.writerow(str(time)+str(wind)+str(date)+'\n')
if row_count == 74:
print "74"
break
印刷結果は問題ありませんが、そうでないファイルです。私は得る:
Title 1,Title 2,Title 3
0,5,:,5,3,C,a,l,m,0,8,"
作成された CSV ファイルの問題点は次のとおりです。
- タイトルが間違った列に分割されています。列 2 には、「1,Title」と「title 2」があります。
- データが間違った場所でカンマ区切りになっている
- スクリプトが新しい行を書き込むと、下から追加するのではなく、前の行に上書きします。
何かご意見は?