使用请求库如何创建多值int参数? 我试图给google maps api起源,但无法正确编码
start_coordinates = {'latitude':40.970321, 'longitude' :29.060873}
end_coordinates = {'latitude':41.029967, 'longitude' :28.974656}
start_latitude = start_coordinates.get('latitude')
start_longitude = start_coordinates.get('longitude')
end_latitude = end_coordinates.get('longitude')
end_longitude = end_coordinates.get('latitude')
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = {
'origin' : '%s,%s' %(start_latitude,start_longitude),
'destination' : '%s,%s' %(end_latitude, end_longitude),
'sensor' : 'false',
}
google_response = requests.get(url,params=params)
google_response
是:
u'http://maps.googleapis.com/maps/api/directions/json?origin=40.970321%2C29.060873&destination=28.974656%2C41.029967&sensor=false'
但它应该是:
u'http://maps.googleapis.com/maps/api/directions/json?origin=40.970321,29.060873&destination=28.974656,41.029967&sensor=false'
其中参数应为origin=40.970321,29.060873
而不是destination=28.974656%2C41.029967
进一步的例子:
这显然是我的错误:
well this is embarrassing. It was my first few lines that threw the code off, it should be:
start_coordinates = {'latitude':40.970321, 'longitude' :29.060873}
end_coordinates = {'latitude':41.029967, 'longitude' :28.974656}
start_latitude = start_coordinates.get('latitude')
start_longitude = start_coordinates.get('longitude')
end_latitude = end_coordinates.get('latitude')
end_longitude = end_coordinates.get('longitude')
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = {
'origin' : '%s,%s' %(start_latitude,start_longitude),
'destination' : '%s,%s' %(end_latitude, end_longitude),
'sensor' : 'false',
}
google_response = requests.get(url, params=params)
我的end_longitude
和end_latitude
错了。所以这解决了它
答案 0 :(得分:1)
如果您坚持使用decodec网址,请尝试以下网址:
In [54]: urllib.unquote(google_response.url).decode('utf8')
Out[54]: u'http://maps.googleapis.com/maps/api/directions/json?origin=40.970321,29.060873&destination=28.974656,41.029967&sensor=false'
编辑:当urllib更改排序时(我认为这是由于在内部使用dict),此方法也不起作用。我建议通过pythons string-concatenation / formating方法手动构建url。