讀取頁面返回字典值提示錯誤:TypeError: string indices must be integers, not str


路由器get_rand_key.cgi返回用於后續AES加密的隨機數,該返回值是字典。

如下代碼,

print pagetext返回字典{"rand_key":"c9d8b128f26058c5a684a212100bba0204beaf1795d227da4601869dd83045cd"}

print pagetext['rand_key']提示錯誤TypeError: string indices must be integers, not str

import urlparse  
import urllib  
import urllib2   
import string  
import json

randomkey_url = 'http://192.168.0.1/router/get_rand_key.cgi'
request = urllib2.Request(randomkey_url)
response = urllib2.urlopen(request)
pagetext = response1.read()
print pagetext
print pagetext['rand_key']

 

解決方法:

在瀏覽器調試中看到返回的json,修改代碼如下

import urlparse  
import urllib  
import urllib2   
import string  
import json

randomkey_url = 'http://192.168.0.1/router/get_rand_key.cgi'
request = urllib2.Request(randomkey_url)
response = urllib2.urlopen(request)
pagetext = json.load(response)
print pagetext
print pagetext['rand_key']

執行結果

{u'rand_key': u'260efad1f2c85451a60c09ee96e11f6c754dade635a10b43c681df39fddca5e0'}
260efad1f2c85451a60c09ee96e11f6c754dade635a10b43c681df39fddca5e0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM