python开发

TypeError:string indices must be

2018-11-27  本文已影响1012人  想旅游的程序员

问题描述:通过fiddler找到指定的端口,获取到想要的json数据,但是在筛选数据时,出现了以上的错误

{
    "error_code": 0,
    "list": [{
        "hero_id": "129",
        "name": "上官婉儿",
        "cover": "http:\/\/pic.wankacn.com\/2018-11-13_5bea360053aa8.png",
        "type": ["2"],
        "tags": 1
    }
   .....
   .....
   .....

正常的操作应该是

print(result['error_code'])

这时的结果应该是0

注:实际结果为TypeError:string indices must be integers

解决办法

需要引入json模块,再执行print(json.loads(result['error_code']))

以下是源代码,对王者荣耀盒子所有英雄的抓取

import requests
import json

result = requests.get('http://gamehelper.gm825.com/wzry/hero/list?channel_id=90001a&app_id=h9044j&game_id=7622&game_name=%E7%8E%8B%E8%80%85%E8%8D%A3%E8%80%80&vcode=13.0.2.1&version_code=13021&cuid=2ABF1E53291068786594240D77B54577&ovr=4.4.2&device=HUAWEI+_HUAWEI+MLA-AL10&net_type=1&client_id=7w0cv%2BaysYce1FlgGgJX8A%3D%3D&info_ms=DanZQw1N0z4Bj0HxbaP48g%3D%3D&info_ma=2He45aFvHvPkuUZrcj7tnQfztiUwLGcrZZTydNpuZM4%3D&mno=0&info_la=HnsCMQrvfAXjg2Bdt9pyQg%3D%3D&info_ci=HnsCMQrvfAXjg2Bdt9pyQg%3D%3D&mcc=0&clientversion=13.0.2.1&bssid=2He45aFvHvPkuUZrcj7tnQfztiUwLGcrZZTydNpuZM4%3D&os_level=19&os_id=507b9d3402088775&resolution=720_1280&dpi=240&client_ip=192.168.13.28&pdunid=d3402088775507b9')

content = result.content.decode("utf8")
# 这里将str类型的content转换成了dict类型的
content = json.loads(content)
print(len(content["list"]))
for i in range(0,len(content['list'])):
    # 这里的strip('\\')是去除字符串内部的所有'\'
    hero_img = content['list'][i]['cover'].replace("\\",'')
    print(content['list'][i]['name']+hero_img)
上一篇下一篇

猜你喜欢

热点阅读