SJuan_err 2023-09-08 16:49 采纳率: 0%
浏览 43

高德地图API爬取,代码运行之后出现KeyError

高德地图API爬取,代码运行之后出现KeyError(‘cost’),是为什么呀?

img

以下是源码:

import json
from urllib import request

OD=open('od_walking.txt').read().splitlines()

url_base='https://restapi.amap.com/v5/direction/bicycling?parameters&key=47e4ca6d9cd2c2e62b9e300dcd1a8370&origin={0},{1}&destination={2},{3}'

output=open('one_wsy.txt','wb')

for i in OD:
    x1,y1,x2,y2=i.split('\t')
    url=url_base.format(x1,y1,x2,y2)
    try:
        html=request.urlopen(url,timeout=15).read()
        js=json.loads(html)
        d=js['route']['paths'][0]['distance']
        c=js['route']['paths'][0]['cost']['duration']
        out='{0}\t{1}\n'.format(d,c)
        output.write(out.encode('utf8'))
    except Exception as e:
        print(repr(e))
        output.write(url.encode('utf8'))

output.close()


  • 写回答

3条回答 默认 最新

  • 逆夏1130 2023-09-08 16:59
    关注

    报错显示不存在cost这个键,你可以看下js['route']['paths'][0]

    评论

报告相同问题?

问题事件

  • 创建了问题 9月8日