python3 错误string indices must be integers 的解决方法

系统管理员 2021-07-28 19:55 2291阅读 0赞

这个错误意思是字符串的下标一定要是整数
出这种错误有多种可能,最形象直接的就是:

  1. a = '[abc]'
  2. print(a['0'])

有点pyhton基础的都知道下标怎么能是字符串’0’,必须是整数0,1,2,3…

  1. a = '[abc]'
  2. print(a[0])

才是正确的

第二种是json格式导致的错误:

  1. #部分代码
  2. skuid = re.findall('https://item.jd.com/(\d+).html',response.url)[0]
  3. price_url = 'https://p.3.cn/prices/mgets?skuIds=J_{}'.format(skuid)
  4. print(price_url,'7777777777777')
  5. res = requests.get(price_url)
  6. print(res.text,'**********')
  7. print(item,'&&&&&&&&&&&&&')

报错如下:

  1. https://p.3.cn/prices/mgets?skuIds=J_100000822981 7777777777777
  2. [{"op":"4499.00","m":"9999.00","id":"J_100000822981","p":"4499.00"}]
  3. **********
  4. Traceback (most recent call last):
  5. File "/home/python/PycharmProjects/untitled/jd/selenium1.py", line 80, in <module>
  6. jsp.run()
  7. File "/home/python/PycharmProjects/untitled/jd/selenium1.py", line 72, in run
  8. self.get_response_from_page()
  9. File "/home/python/PycharmProjects/untitled/jd/selenium1.py", line 26, in get_response_from_page
  10. data = self.get_data_from_response(response)
  11. File "/home/python/PycharmProjects/untitled/jd/selenium1.py", line 55, in get_data_from_response
  12. item['价格'] = res.text[0]['p']
  13. TypeError: string indices must be integers

因为获取价格url的response(res)是个json数据,所以要json.loads(),才能把json格式转为python识别的格式。
正解:

  1. skuid = re.findall('https://item.jd.com/(\d+).html',response.url)[0]
  2. price_url = 'https://p.3.cn/prices/mgets?skuIds=J_{}'.format(skuid)
  3. print(price_url,'7777777777777')
  4. res = requests.get(price_url)
  5. print(res.text,'**********')
  6. item['价格'] = json.loads(res.text)[0]['p']
  7. print(item,'&&&&&&&&&&&&&')

发表评论

表情:
评论列表 (有 0 条评论,2291人围观)

还没有评论,来说两句吧...

相关阅读