python - 为什么我的 Google Maps API 请求的填充速度如此缓慢?
问题描述
我正在尝试在 python3(使用 Jupyter 笔记本)中编写一个脚本,该脚本使用 Google Maps Geocoding API 查询每个地址的坐标。Google 施加的限制是每秒 50 个请求,但我的代码运行速度要慢得多(处理 1000 行可能需要 20 分钟)。
我正在使用python requests 库进行api 调用,并使用pandas 执行数据转换(即将json 输出解析为所需格式)。我正在分批输入我的输入,以避免在意外异常的情况下丢失我的所有输出。
我的问题是,为什么每次迭代都需要这么长时间?!我对此很陌生,所以我很难确定是什么让我慢了下来。
代码片段:
def populate_coordinates(list_of_addresses, api = api_key):
filled_table = pd.DataFrame({"Pickup address": [],
"Status": [],
#"Postal": [],
"Formatted address": [],
"Lat": [],
"Long": [],
"Location type": []})
count = 0
requests.packages.urllib3.disable_warnings()
for address in list_of_addresses:
data = {"address": address,
"key": api,
"region": "us"}
response = requests.get(endpoint, params = data, verify = False)
response_json = response.json()
if response_json["status"] == "OK":
#address_comp = pd.DataFrame(response_json["results"][0]["address_components"])
#postal = address_comp[address_comp["types"]=="postal_code"]["long_name"][0]
fmt_add = response_json["results"][0]["formatted_address"]
lat = response_json["results"][0]["geometry"]["location"]["lat"]
long = response_json["results"][0]["geometry"]["location"]["lng"]
loc_type = response_json["results"][0]["geometry"]["location_type"]
filled_table = filled_table.append({"Pickup address": address,
"Status": response_json["status"],
#"Postal": postal,
"Formatted address": fmt_add,
"Lat": lat,
"Long": long,
"Location type": loc_type}, ignore_index = True)
else:
filled_table = filled_table.append({"Pickup address": address,
"Status": response_json["status"],
#"Postal": None,
"Formatted address": None,
"Lat": None,
"Long": None,
"Location type": None }, ignore_index = True)
count+=1
print ("Processing: {} of {} addresses".format(count, len(list_of_addresses)))
return filled_table
这是批处理部分(如果相关):
batch_sz = 2000
num_batch = 0
num_entries = 0
results = pd.DataFrame({"Pickup address": [],
"Status": [],
"Formatted address": [],
"Lat": [],
"Long": [],
"Location type": []})
while num_entries<len(addresses):
num_batch+=1
batch_complete = populate_coordinates(addresses[num_entries:num_entries+batch_sz])
num_entries+=batch_sz
results = pd.concat([results, batch_complete], sort = False)
欢迎任何其他提示/建议!
解决方案
这可能需要很长时间,因为当您使用任何 API 方法请求数据时,您会发出 HTTP 请求以检索 JSON 格式的响应,但这当然不是原因。我也尝试了几次 Google Map API,我认为尝试这么多请求可能会变得更慢。因为有时这种网站会在有限的时间内给你有限的请求。
解析过程也可能需要时间。
推荐阅读
- python - 使用外部数据文件将 Qt/PySide 应用程序部署到 macOS
- mongodb - 我想检查 mongo db 中的集合,其中 pixel="446" 在控制台中打印 _id 并在本地创建一个文件来保存数据 - 在 JAVA 中
- python - 如何在 python numba JIT 模式下加载文件
- javascript - 指令如何在 DOM 中的某些父元素上播放动画?
- dialogflow-es - 如何将 LiveChat Dashboard 与 Google Dialogflow 集成以进行代理交接?
- python - 为什么 Python 中的 `str(1) is '1'` `True` 不是?
- c++ - 可以在 getline 的循环中使用 to_string 吗?
- python - 如何在 SHELL SCRIPT 中比较文件名
- python - 使用 Pycaret 和 plotly 的奇怪时间序列图
- javascript - Angular 10 中的范围滑块不适用于十进制值