2016-03-31 20 views
0

我試圖從Verizon的回購定價站點中獲取數據。我在瀏覽器中瀏覽「網絡」請求時發現了信息的來源。該網站是JSON格式,但沒有我會讓我下載該數據https://www.verizonwireless.com/vzw/browse/tradein/ajax/deviceSearch.jsp?act=models&car=Verizon&man=Apple&siz=largePython-無法從JSON源中拉JSON格式

我不記得我試過的一切,但這裏是我遇到的問題。另外,我不確定如何插入多個代碼塊。

import json,urllib,requests 
res=urllib.request.urlopen(url) 
data=json.loads(res) 
TypeError: the JSON object must be str, not 'bytes' 

import codecs 
reader=codecs.getreader('utf-8') 
obj=json.load(reader(res)) 
ValueError: Expecting value: line 1 column 1 (char 0) 
#this value error happens with other similar attempts, such as.... 
res=requests.get(url) 
res.json()#Same error Occurs 

在這一點上,我研究了很多小時,找不到解決方案。我假設該網站沒有正常格式化,或者我錯過了明顯的東西。我在我的Web開發人員工具中看到了JSON請求/結構。

有沒有人有任何想法或解決方案呢?如果您有任何問題,請告訴我。

+0

這是因爲Verizon正在發回一個HTML頁面埋HTML標籤內JSON-看的東西,而不是一個JSON格式的字符串(這是什麼'。 json()'作爲輸入)。 [這個答案](http://stackoverflow.com/questions/13323976/how-to-extract-a-json-object-that-was-defined-in-a-html-page-javascript-block-us)應該幫你。 –

回答

0

您需要發送一個User-Agent HTTP頭字段。試試這個程序:

import requests 

url='https://www.verizonwireless.com/vzw/browse/tradein/ajax/deviceSearch.jsp?act=models&car=Verizon&man=Apple&siz=large' 
# Put your own contact info in next line 
headers = {'User-agent':'MyBot/0.1 ([email protected])'} 
r = requests.get(url, headers=headers) 
print(r.json()['models'][0]['name']) 

結果:

iPhone 6S