我使用谷歌地点API编写了一个用于获取电话号码的小程序,但速度非常慢。当我测试6个项目时,需要4.86秒至1.99秒不等,而我不确定时间变化的原因。我很少接触API,所以甚至不知道可以/无法加速哪些内容,哪些内容留给服务API的Web服务器处理,以及我可以自己改变什么。
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))