码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-12-04 13:50:49      阅读:1340      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   color   sp   on   div   log   

路由器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

 

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

标签:style   blog   http   ar   color   sp   on   div   log   

原文地址:http://www.cnblogs.com/wangjibo/p/4142559.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!