gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:40 25 4
gpt4 key购买 nike

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

关于python - 请求多值参数的url编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20241655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com