2015-06-15 33 views
1

我正在做一些刮,看着像這樣的一個頁面(https://www.endomondo.com/rest/v1/users/20261627/workouts/526622897),但我還沒有能夠完全檢索JSON內容。我曾嘗試使用兩個下面的代碼集,但每個返回一個不完整的JSON對象:Python3的請求模塊或urllib.request模塊都檢索不完整的json

url = 'https://www.endomondo.com/rest/v1/users/%s/workouts/%s'%(string_use_user, string_use_workout) 
    print(url) 
    response = urlopen(url) 
    try: 
     reader = codecs.getreader("utf-8") 
     print(reader(response)) 
     jsonresponse = json.load(reader(response)) 
     print(jsonresponse) 

,同樣使用響應庫代替的urllib也未能檢索完整JSON

​​

在這兩種情況下,我得到大約是JSON的1/4。例如,在這種情況下: https://www.endomondo.com/rest/v1/users/20261627/workouts/526622897

我接收:

{'feed_id': 281475471235835, 'id': 526622897, 'duration': 4082.0, 'local_start_time': '2015-05-21T09:30:45.000+02:00', 'calories': 1073.0, 'tagged_users': [], 'altitude_max': 69.9523, 'sport': 0, 'distance': 11.115419387817383, 'altitud\ 
e_min': 14.9908, 'include_in_stats': True, 'hydration': 0.545339, 'start_time': '2015-05-21T07:30:45.000Z', 'ascent': 137.162, 'is_live': False, 'pb_count': 2, 'playlist': [], 'is_peptalk_allowed': False, 'weather': {'wind_speed': 11, '\ 
temperature': 12, 'wind_direction': 13, 'type': 3, 'humidity': 81}, 'speed_max': 24.8596, 'author': {'name': 'gfdgfd', 'id': 20261627, 'last_name': 'gdsgsk', 'gender': 0, 'expand': 'abs', 'picture': {'url': 'https://www.endom\ 
ondo.com/resources/gfx/picture/18511427/thumbnail.jpg'}, 'first_name': 'gdsgds', 'viewer_friendship': 1, 'is_premium': False}, 'sharing': [{'share_time': '2015-05-21T08:45:19.000Z', 'type': 0, 'share_id': 1635690786663532}], 'show_map':\ 
0, 'pictures': [], 'hashtags': [], 'descent': 150.621, 'speed_avg': 9.80291763746756, 'expand': 'full', 'show_workout': 0, 'points': {'expand': 'ref', 'id': 2199549878449}} 

我無法接收的數據內的長陣列。我甚至沒有恢復所有的非數組數據。

我通過JSON驗證器運行了原始頁面,並沒有問題。同樣,我運行了我通過驗證器收到的JSON,這也很好 - 除非我與原始文件進行比較,否則它不會顯示任何遺漏的跡象。

我很感激任何關於如何排除故障的建議。謝謝。

回答

3

看起來像這個API正在做一些User-Agent sniffing,只發送它認爲是真正的網頁瀏覽器的完整內容。

一旦您設置一個User-Agent頭有一個共同的瀏覽器UA字符串,你得到充分的響應:

>>> UA = 'Mozilla/5.0 (X11; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0' 
>>> url = 'https://www.endomondo.com/rest/v1/users/20261627/workouts/526622897' 
>>> r = requests.get(url, headers={'User-Agent': UA}) 
>>> 
>>> print len(r.content) 
96412 

requests文檔,詳細瞭解setting custom headers

+0

打我吧:)事實上,UA可以是任何字符串... – junnytony