Skip to main content
 首页 » 编程设计

python之请求多值参数的url编码

2025年05月04日6yyy_WW

如何使用请求库制作多值 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

进一步的例子:

这不起作用: http://maps.googleapis.com/maps/api/directions/json?origin=40.970321%2C29.060873&destination=28.974656%2C41.029967&sensor=false

这有效: http://maps.googleapis.com/maps/api/directions/json?origin=40.970321,29.060873&destination=41.029967,28.974656&sensor=false


这显然是我的错误:

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。所以这修复了它

请您参考如下方法:

如果你坚持使用解码器 url,试试这个:

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 更改了顺序(我认为这是由于在内部使用字典),此方法也不起作用。我建议通过 python 字符串连接/格式化方法手动构建 url。