TypeError:字符串索引必须是整数和ValueError

时间:2013-03-26 11:43:51

标签: python typeerror

我想迭代数据并只下载登录但我收到此错误:

print elem["login"]
TypeError: string indices must be integers, not str

我的代码:

import requests
import json
import csv
import urllib

 def printContents(path):
    filein = open(path, 'r')
    instr = filein.read()
    filein.close()
 printContents("top_story_2012.txt")
 appkey = "...."
 url= "http://a.wykop.pl/ludzie/followers/"
 wykopff = open("top_story_2012.txt", 'r')
 names = [line.strip() for line in wykopff.readlines()]
 for i in names:
    p = urllib.urlopen(url + i + "/appkey/" + appkey)
    wykops = p.read()
    read = json.loads(wykops)
    for elem in wykops:
        print elem["login"]

我尝试将'login'更改为整数:

   print elem[int("login")]

我不确定这是不是这样做但它仍然不起作用然后我得到这个错误:

 ValueError: invalid literal for int() with base 10: 'login'

我试图迭代的内容如下所示:

  {"login":"Josif6969","email":"a9a4525e207fcba3ac0fc221246439a3:3670009297","public_email":"","name":"","www":"","jabber":"","gg":"","city":"","about":"Hobby: Obserwator.","author_group":1,"links_added":82,"links_published":4,"comments":132,"rank":0,"followers":       

1 个答案:

答案 0 :(得分:0)

您希望循环使用已解码的JSON结构read

wykops = p.read()
read = json.loads(wykops)
for elem in read:
    print elem["login"]

或者,将其简化为使用json.load()代替:

for elem in json.load(p):
    print elem["login"]

这假设来自json.load()调用的数据是一个列表,但我认为您只是想将结果视为字典:

data = json.load(p):
print data["login"]

听起来(来自评论)好像某些的响应会返回一个列表。试试这个来弄清楚发生了什么:

data = json.load(p):
try:
    print data["login"]
except TypeError:
    # not a dictionary, so what is it *then*?
    print "Not a dictionary:", data

您的代码是逐个循环遍历JSON数据字符串,因此您尝试将["login"]应用于python字符串:

>>> 'somestring'["login"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str