【发布时间】:2018-03-16 06:38:16
【问题描述】:
我正在尝试从多个气象站抓取 Weather Underground 多年的每小时数据,并将其放入 pandas 数据框中。我不能使用 API,因为请求有限制,我不想支付数千美元来抓取这些数据。
我可以让脚本从一个站点抓取我想要的所有数据。当我尝试修改它以循环遍历站点列表时,我要么收到 406 错误,要么只返回列表中第一个站点的数据。如何循环遍历所有站点?另外,如何存储电台名称以便将其添加到另一列的数据框中?
这是我的代码现在的样子:
stations = ['EGMC','KSAT','CAHR']
weather_data = []
date = []
for s in stations:
for y in range(2014,2015):
for m in range(1, 13):
for d in range(1, 32):
#check if a leap year
if y%400 == 0:
leap = True
elif y%100 == 0:
leap = False
elif y%4 == 0:
leap = True
else:
leap = False
#check to see if dates have already been scraped
if (m==2 and leap and d>29):
continue
elif (y==2013 and m==2 and d > 28):
continue
elif(m in [4, 6, 9, 11] and d > 30):
continue
timestamp = str(y) + str(m) + str(d)
print ('Getting data for ' + timestamp)
#pull URL
url = 'http://www.wunderground.com/history/airport/{0}/' + str(y) + '/' + str(m) + '/' + str(d) + '/DailyHistory.html?HideSpecis=1'.format(stations)
page = urlopen(url)
#find the correct piece of data on the page
soup = BeautifulSoup(page, 'lxml')
for row in soup.select("table tr.no-metars"):
date.append(str(y) + '/' + str(m) + '/' + str(d))
cells = [cell.text.strip().encode('ascii', 'ignore').decode('ascii') for cell in row.find_all('td')]
weather_data.append(cells)
weather_datadf = pd.DataFrame(weather_data)
datedf = pd.DataFrame(date)
result = pd.concat([datedf, weather_datadf], axis=1)
result
【问题讨论】:
标签: python pandas url web-scraping beautifulsoup