【问题标题】:Python: How do I utilize the .json function over a list of get requests?Python:如何在获取请求列表上使用 .json 函数?
【发布时间】:2020-09-10 03:13:14
【问题描述】:

我正在使用距离矩阵 API 来获取在两点之间移动所需的时间,但在调用我的获取请求列表中的 .json 函数时遇到问题。

#creates url for API call to get travel time between two cities (my list includes 7 origin and destination pairs)
full_url = [f'{url}+"origins="+{item}+"&destinations="+{row}+"&key="+{apikey}' for item, row in zip(origin, destination)]

#get request to API
r = [requests.get(url) for url in full_url]

#calls .json on each get request in r
time = []
for response in r:
    time.append(response.json()['rows'][0]['elements'][0]['duration']['text'])

当我调用 .json 时出现错误:

AttributeError: 'bytes' 对象没有属性 'json'

如何使用 for 循环在 r 的每个元素上调用 .json?

【问题讨论】:

  • 您使用的是哪个版本的请求模块?
  • 我使用的是 requests 模块的 2.22.0 版本
  • 奇怪的是,看起来您的 requests.get 正在返回 bytes 而不是 Response 对象。你能扩展你的例子吗?

标签: python json python-requests


【解决方案1】:

json.loads() 会解决你的问题。

我创建了一个带有 3 个测试 URL 的虚拟例程来演示。

import pandas as pd
import requests, json

API_key = 'xxxxx___yourkeyhere'

urls = [
    'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=' + API_key,
    'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Houston,TX&destinations=New+York+City,NY&key=' + API_key,
    'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Reno,NV&destinations=New+York+City,NY&key=' + API_key,
]

time = []
for url in urls: 
    r = requests.get(url)
    if r.status_code==200:
        data = json.loads(r.text)
        time.append(data['rows'][0]['elements'][0]['duration']['text'])
print(time)

['3 hours 44 mins', '23 hours 58 mins', '1 day 15 hours']

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多