我正在尝试从他们的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”
- 数据在错误的地方用逗号划定
- 当脚本写入新行时,它会覆盖前一行,而不是从底部追加。
有什么想法吗?