2016-04-13 18 views
1

jsonファイルにスクラップしたデータをダンプします。私はそれがすでに良い形式(辞書、リスト、文字列など)であると信じています。どのようにjsonファイルに出力できますか?JSONファイルへのダンプPython辞書

作業ディレクトリ内のファイル output.jsonに辞書を書き込むことが起こっている
with open('output.json', 'w') as jsonFile: 
    json.dump(scrapedData, jsonFile) 

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

from bs4 import BeautifulSoup 
import urllib 
import json 

    def main(): 
     """weather scraper""" 
     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") 

    scrapedData = {} 
    for table in tables: 
     print 'Weather Philadelphia' 

     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[firstTd.text] = values 

    print scrapedData 

    if __name__ == "__main__": 
     main() 

答えて

0

次を使用する必要があります。
open('output.json', 'w')の代わりにopen('C:\Users\user\Desktop\output.json', 'w')のようなフルパスを指定すると、ファイルをユーザーのデスクトップに出力できます。

+0

ありがとう!私はそれを保存する場所をどのように指定できるのか知っていますか?これで、自動的にドキュメントに保存されます。 – malina

+0

@malina私は自分の答えを編集しました。それがあなたの問題を解決したかどうか教えてください。 – Rafael

+0

それはあなたに感謝しました:) – malina