2016-05-17 5 views
1

天気予報サイトwunderground.comからデータを取得しようとしています。 1941年から2016年の間、毎月フィラデルフィア出身(jan-dec)になりたい。天気データの出力ファイルが空になります

は、最初に私はこのコードを持っていたが、これは唯一のかき取り、1月2016

#!/usr/bin/python 
#weather.scraper 

from bs4 import BeautifulSoup 
import urllib 
import json 

def main(): 
    # weatherData = weather_philadelphia_data #Json beginns here 
    # with open(jsonfile, 'w') as outputFile: 
    #  json.dump(weatherData, outputFile) 
    # #scrapping beginns here 
    r = urllib.urlopen("https://www.wunderground.com/history/airport/KPHL/2016/1/1/MonthlyHistory.html?&reqdb.zip=&reqdb.magic=&reqdb.wmo=&MR=1").read() 
    soup = BeautifulSoup(r, "html.parser") 
    tables = soup.find_all("table", class_="responsive airport-history-summary-table") 

    weatherdata = [] 
    for table in tables: #reason for it to do it 12x 

     for tr in table.find_all("tr"): 
      firstTd = tr.find("td") 
      if firstTd and firstTd.has_attr("class") and "indent" in firstTd['class']: 
       values = {} 
       tds = tr.find_all("td") 
       maxVal = tds[1].find("span", class_="wx-value") 
       avgVal = tds[2].find("span", class_="wx-value") 
       minVal = tds[3].find("span", class_="wx-value") 
       if maxVal: 
        values['max'] = maxVal.text 
       if avgVal: 
        values['avg'] = avgVal.text 
       if minVal: 
        values['min'] = minVal.text 
       if len(tds) > 4: 
        sumVal = tds[4].find("span", class_="wx-value") 
        if sumVal: 
         values['sum'] = sumVal.text 
       scrapedData = {} 
       scrapedData[firstTd.text] = values 
       weatherdata.append(scrapedData) 
     break 
    with open ("january_2016.json", 'w') as outFile: 
     json.dump(weatherdata, outFile, indent=2) 


print "done" 
if __name__ == "__main__": 
    main() 

用のファイルを作った私はすべての年と月をループforループを作ってみました。それはファイルを作るが、それはデータで空である、それは年だけを示す。 これは新しいコードです:

#!/usr/bin/python 
#weather.scraper 
from bs4 import BeautifulSoup 
import urllib 
import json 

allData = [] 
# this loops through all the Weather years 
for y in range(1941, 2017): 
    yearData = {} 
    yearData['year'] = y 
    months = [] 
    for m in range(1, 13): 
     def main(): 
     # weatherData = weather_philadelphia_data #Json beginns here 
     # with open(jsonfile, 'w') as outputFile: 
     #  json.dump(weatherData, outputFile) 
     # scrapping beginns here 
      url = "https://www.wunderground.com/history/airport/KPHL/%d/%d/1/MonthlyHistory.html" % (y, m) 
      r = urllib.urlopen(url).read() 
      soup = BeautifulSoup(r, "html.parser") 
      tables = soup.find_all("table", class_="responsive airport-history-summary-table") 

      weatherPerMonth = {} 
      weatherdata = [] 
      for table in tables: #reason for it to do it 12x 

       for tr in table.find_all("tr"): 
        firstTd = tr.find("td") 
        if firstTd and firstTd.has_attr("class") and "indent" in firstTd['class']: 
         values = {} 
         tds = tr.find_all("td") 
         maxVal = tds[1].find("span", class_="wx-value") 
         avgVal = tds[2].find("span", class_="wx-value") 
         minVal = tds[3].find("span", class_="wx-value") 
         if maxVal: 
          values['max'] = maxVal.text 
         if avgVal: 
          values['avg'] = avgVal.text 
         if minVal: 
          values['min'] = minVal.text 
         if len(tds) > 4: 
          sumVal = tds[4].find("span", class_="wx-value") 
          if sumVal: 
           values['sum'] = sumVal.text 
         scrapedData = {} 
         scrapedData[firstTd.text] = values 
         weatherdata.append(scrapedData) 
         break 
      monthData = {} 
      monthData['month'] = m 
      monthData['weather'] = weatherPerMonth 
      months.append(monthData) 
     yearData['months'] = months 
     allData.append(yearData) 

     with open ("allData_philly.json", 'w') as outFile: 
      json.dump(allData, outFile, indent=2) 


print "done" 
if __name__ == "__main__": 
    main() 

これは出力ファイルの一部です。

[ 
{ 
    "months": [], 
    "year": 1941 
}, 
] 

それは問題は次の通りである。このそれまでは2016年

ようなものです。 私は年間1941から2016のための12ヶ月(1月 - 12月)のために私にweatherdataを与えるファイルをしたい、それがこのようなものになります。

[ 
    { 
    "months": [{ 
       'month': 12 
       'weather' : { 
        "Max Temperature": { 
        "max": "18", 
        "avg": "6", 
        "min": "-2" 
        } 
       }, 
       { 
        "Mean Temperature": { 
        "max": "12", 
        "avg": "1", 
        "min": "-6" 
        } 
       }, 
       { 
        "Min Temperature": { 
        "max": "6", 
        "avg": "-3", 
        "min": "-11" 
        } 

     }], 
    "year": 1941 
    }, 
] 

をしかし、なぜ、私の、私は把握することはできませんコードが動作していない、私は誰かが助けることを願っています!

答えて

1

あなたのコードはうまく見えますが、正しい出力を得ることができないような小さなものがいくつかあります。

  • def main():は、ループの内側にあるので、あなたはmain()を呼び出すとき、それはすべての年をループしませんされています。あなたの最初の例ではうまく見えます。
  • weatherPerMonthを空のリストとして宣言し、monthData['weather']に割り当てます。実際のデータはweatherdataですが、決してどこにでも書き込まれることはありません。
  • 以下のコードは、ごくわずかなコードの変更、いくつかの並べ替え、インデントの変更ですが、必要な出力が得られるはずです。

#weather.scraper 
from bs4 import BeautifulSoup 
import urllib.request 
import json 

allData = [] 
# this loops through all the Weather years 
for y in range(2012, 2014): 
    yearData = {} 
    yearData['year'] = y 
    months = [] 
    for m in range(1, 13): 
     # weatherData = weather_philadelphia_data #Json beginns here 
     # with open(jsonfile, 'w') as outputFile: 
     #  json.dump(weatherData, outputFile) 
     # scrapping beginns here 
     url = "https://www.wunderground.com/history/airport/KPHL/%d/%d/1/MonthlyHistory.html" % (y, m) 
     r = urllib.request.urlopen(url).read() 
     soup = BeautifulSoup(r, "html.parser") 
     tables = soup.find_all("table", class_="responsive airport-history-summary-table") 

     weatherPerMonth = {} 
     weatherdata = [] 

     monthData = {} 

     for table in tables: #reason for it to do it 12x 

      for tr in table.find_all("tr"): 
       firstTd = tr.find("td") 
       if firstTd and firstTd.has_attr("class") and "indent" in firstTd['class']: 
        values = {} 
        tds = tr.find_all("td") 

        maxVal = tds[1].find("span", class_="wx-value") 
        avgVal = tds[2].find("span", class_="wx-value") 
        minVal = tds[3].find("span", class_="wx-value") 
        if maxVal: 
         values['max'] = maxVal.text 
        if avgVal: 
         values['avg'] = avgVal.text 
        if minVal: 
         values['min'] = minVal.text 
        if len(tds) > 4: 
         sumVal = tds[4].find("span", class_="wx-value") 
         if sumVal: 
          values['sum'] = sumVal.text 
        scrapedData = {} 
        scrapedData[firstTd.text] = values 

        weatherdata.append(scrapedData) 
        monthData['month'] = m 
        monthData['weather'] = values 
        break 


     months.append(monthData) 
    yearData['months'] = months 
    allData.append(yearData) 

with open ("allData_philly.json", 'w') as outFile: 
    json.dump(allData, outFile, indent=2) 
+0

コードを使用すると、Pythonの2を使用する場合、 '輸入urllib.request'が戻ってあなたの元のコードを変更する必要があり、Pythonの3のためです。 –