2016-12-21 38 views
0

我想編寫一個python腳本來獲取來自URL的響應,然後從響應中選擇一個參數並將該值保存在輸出file.format的url輸出是JSON。 我們將在一天內運行一次該腳本,並抓取該值,稍後我們可能必須製作圖表才能看到增量值。 參數是這樣的: 「TotalVolumeConsumedInBytes」:0Python腳本下載和讀取json響應

我是新來的python,所以任何幫助開始將是很好的。 感謝

+1

你看了一下http://docs.python-requests.org/en/master/ - 我覺得第一頁幾乎給你提供解決問題的全部思路 –

回答

0

試試這個,這只是一個例子網址,但它適用於python3:

import requests 

req = requests.get('https://raw.githubusercontent.com/Miguel-Frazao/world-data/master/countries_data_assoc.json').json() 
TotalVolumeConsumedInBytes = req['AD']['name'] # Andorra 

# write to file: 
with open('data.txt', 'a') as f: # adjust file path here, this case is on append mode, you you want to rewrite every time change the 'a' to 'w' 
    f.write('TotalVolumeConsumedInBytes: {}'.format(TotalVolumeConsumedInBytes)) 

如果您正在使用python2:

import urllib2 
import json 

req = urllib2.urlopen('https://raw.githubusercontent.com/Miguel-Frazao/world-data/master/countries_data_assoc.json') 
req = json.load(req) 
param = req['AD']['name'] # Andorra 

# write to file: 
with open('tests.txt', 'a') as f: 
    f.write(param) 
0

恕我直言,最好的辦法是使用urllib3Here您可以找到一步一步的使用示例,它與您在獲取JSON數據時所做的描述非常相似。