2016-04-13 105 views
1

我想將我廢棄的數據轉儲到json文件中。我相信它已經是一個很好的格式(字典,列表,字符串等)我怎樣才能輸出到JSON文件?將Python字典轉儲到JSON文件

#!/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

您需要使用以下方法:

with open('output.json', 'w') as jsonFile: 
    json.dump(scrapedData, jsonFile) 

哪裏會寫字典的output.json文件在工作目錄。
您可以提供完整路徑,例如open('C:\Users\user\Desktop\output.json', 'w')而不是open('output.json', 'w'),例如將文件輸出到用戶的桌面。

+0

非常感謝你!你也知道我怎麼能指定在哪裏保存它?現在,它會自動將它保存到我的文檔中。 – malina

+0

@malina我編輯了我的答案。請讓我知道,如果這解決了你的問題。 – Rafael

+0

它確實謝謝你:) – malina