【问题标题】:How to encode latitude and longitude using urllib.parse.urlencode?如何使用 urllib.parse.urlencode 对纬度和经度进行编码?
【发布时间】:2020-05-26 08:18:21
【问题描述】:

我正在使用 Google API 来获取附近咖啡店的 json 数据。为此,我需要将纬度和经度编码到 URL 中。

必填网址:https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee&location=22.303940,114.170372&radius=1000&maxprice=3&key=myAPIKey

我使用 urlencode 获取的 URL:https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee&location=22.303940%2C114.170372&radius=1000&maxprice=3&key=myAPIKEY

如何删除 URL 中的“%2C”? (我在下面展示了我的代码)

serviceurl_placesearch = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
    parameters = dict()
    query = input('What are you searching for?')     
    parameters['query'] = query

parameters['location'] = "22.303940,114.170372"

while True:
    radius = input('Enter radius of search in meters: ')
    try:
        radius = int(radius)
        parameters['radius'] = radius
        break
    except:
        print('Please enter number for radius')

while True:
    maxprice = input('Enter the maximum price level you are looking for(0 to 4): ')
    try:
        maxprice = int(maxprice)
        parameters['maxprice'] = maxprice
        break
    except:
        print('Valid inputs are 0,1,2,3,4')
parameters['key'] = API_key

url = serviceurl_placesearch + urllib.parse.urlencode(parameters)

我添加了这段代码以使 URL 正常工作,但我认为这不是一个长期的解决方案。我正在寻找更长期的解决方案。

urlparts = url.split('%2C')
url = ','.join(urlparts)

【问题讨论】:

  • %2CPercent Encoding 中逗号的编码。您使用的 API 是否需要文字逗号而不是百分比编码版本?
  • @DonRowe ,如果我没有文字逗号,我的 json.loads() 无法处理 json 输出,因此 API 确实需要文字逗号,至少为了获取 json数据。

标签: python url google-api urllib urlencode


【解决方案1】:

你可以加safe=","

import urllib.parse

parameters = {'location': "22.303940,114.170372"}

urllib.parse.urlencode(parameters, safe=',')

结果

location=22.303940,114.170372

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多