首页 > 代码库 > 读取页面返回字典值提示错误:TypeError: string indices must be integers, not str

读取页面返回字典值提示错误: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 jsonrandomkey_url = http://192.168.0.1/router/get_rand_key.cgirequest = 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 jsonrandomkey_url = http://192.168.0.1/router/get_rand_key.cgirequest = urllib2.Request(randomkey_url)response = urllib2.urlopen(request)pagetext = json.load(response)print pagetextprint pagetext[rand_key]

执行结果

{u‘rand_key‘: u‘260efad1f2c85451a60c09ee96e11f6c754dade635a10b43c681df39fddca5e0‘}
260efad1f2c85451a60c09ee96e11f6c754dade635a10b43c681df39fddca5e0

 

读取页面返回字典值提示错误:TypeError: string indices must be integers, not str