我构建了以下小程序,用于使用 google 的 place api 获取电话号码,但它非常慢。当我测试 6 个项目时,它需要 4.86 秒到 1.99 秒,我不确定为什么时间会发生重大变化。我对 API 很陌生,所以我什至不确定哪些事情可以/不能加速,哪些事情留给服务 API 的网络服务器,以及我可以自己改变什么。
import requests,json,time
searchTerms = input("input places separated by comma")
start_time = time.time() #timer
searchTerms = searchTerms.split(',')
for i in searchTerms:
r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
a = r1.json()
pid = a['results'][0]['place_id']
r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
b = r2.json()
phone = b['result']['formatted_phone_number']
name = b['result']['name']
website = b['result']['website']
print(phone+' '+name+' '+website)
print("--- %s seconds ---" % (time.time() - start_time))
最佳答案
您可能希望并行发送请求。 Python 提供 multiprocessing
适合这样的任务的模块。
示例代码:
from multiprocessing import Pool
def get_data(i):
r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
a = r1.json()
pid = a['results'][0]['place_id']
r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
b = r2.json()
phone = b['result']['formatted_phone_number']
name = b['result']['name']
website = b['result']['website']
return ' '.join((phone, name, website))
if __name__ == '__main__':
terms = input("input places separated by comma").split(",")
with Pool(5) as p:
print(p.map(get_data, terms))
关于python - 如何加速 API 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34512646/