如何修复TypeError:字符串索引必须是整数?

时间:2015-09-07 19:32:15

标签: python web-crawler typeerror

运行代码时,会显示以下错误:

File "E:\python343\crawler.py", line 36, in <module>
    if(x2['type']=='status'):
TypeError: string indices must be integers

以下是代码:

#PRINTING YOUR FRIEND ALL "favorite_teams"
fs = g.get_object("me/friends")
for f in fs['data']:
    #print f
    #print f['name'],f['id']
    print (f['name'])
    for x in g.get_object(f['id'])['favorite_teams']:
        print (x['name'])


#SEACHING TOP 10 PAGE ON INPUTTING PAGE NAME AND OUTPUT AS PAGE ID 
x= g.request('search', {'q' : 'TaylorSwift', 'type' : 'page', 'limit' : 1000})['data'][0]['id']

non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)

#GET ALL STATUS POST ON PARTICULAR PAGE(X=PAGE ID)
for x1 in g.get_connections(x, 'feed')['data']:
    print (str(x1).translate(non_bmp_map))
    for x2 in x1:
        print (str(x2).translate(non_bmp_map))
        if(x2['type']=='status'):
            x2['message']

那么如何处理x2['type']修复错误?

希望得到你的帮助,谢谢你。

1 个答案:

答案 0 :(得分:1)

x2是一个字符串而不是响应对象。在其他情况下绕过它并检查x2:

if isinstance(x2, dict):
    if(x2['type']=='status'):
        x2['message']
else:
    # examine the data
    print 'Unexpected data:', type(x2), x2