2017-10-04 7 views
-1

私は複数の気象観測所から何年もの時間データを取得し、それをpandasデータフレームに入れようとしています。リクエストには制限があり、このデータをスクラップするために何千ドルも支払う必要がないため、APIを使用することはできません。Pythonで複数のURLリクエストの値リストをループする

1つのステーションから必要なすべてのデータをスクラップするスクリプトを取得できます。私がそれを修正しようとすると、ステーションのリストをループするので、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 

答えて

0

あなたは、ヘッダーにUser-Agentを追加する必要がありますhttps://httpstatuses.com/406

あなたのエラーの説明です。しかし、私はこのサイトではクロールからいくつかの保護が存在すると思います。あなたはScrapy、Crawlera、プロキシリスト、ユーザエージェントローテータなどのより具体的なものを使用するべきです。

関連する問題