首页 > 解决方案 > 如何在网络抓取中将地理编码 api 密钥与 python 集成

问题描述

我正在尝试使用 google geocode api 来获取一个地方的纬度和经度。我还创建了 geocode api 密钥并将其包含在程序中,但我认为它在代码中的集成存在错误。

我在 python 中使用网络抓取。我还包括了 urllib、json 和 ssl 模块。

我创建了字典来存储位置的 api 键和地址,并创建了 urllib.parse.urlencode() 来像浏览器一样对 url 进行编码。

这是示例代码:

import json
import urllib.request,urllib.parse,urllib.error
import ssl

api_key=False

api_key ='AIza             '

if api_key is False:
    api_key=42
    serviceurl='http://py4e-data.dr-chuck.net/json?'
else:
    serviceurl='https://maps.googleapis.com/maps/api/geocode/json?'

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    address=input('Enter location:')
    if len(address)<1: break

    params=dict()

    params['address']=address

    if api_key is not False: params['key']=api_key

    url=serviceurl+urllib.parse.urlencode(params)

    print('Retrieving', url)
    uh = urllib.request.urlopen(url, context=ctx)
    data = uh.read().decode()
    print('Retrieved', len(data), 'characters')

    try:
        js = json.loads(data)
    except:
        js = None

    if not js or 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue

    print(json.dumps(js, indent=4))

    lat = js['results'][0]['geometry']['location']['lat']
    lng = js['results'][0]['geometry']['location']['lng']
    print('lat', lat, 'lng', lng)
    location = js['results'][0]['formatted_address']
    print(location)

我得到的输出为:

Retrieved 130 characters
==== Failure To Retrieve ====
{
   "error_message" : "This API project is not authorized to use this API.",
   "results" : [],
   "status" : "REQUEST_DENIED"
}

I have created the api key for geocode. But output is request denial. 


标签: pythonapiweb-scrapinggeocode

解决方案


推荐阅读