python - 如何在网络抓取中将地理编码 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.
解决方案
推荐阅读
- neo4j - 用于获取自相关节点的密码模式
- flutter - 结果:IdTokenResult('PlatformIdTokenResult'的实例)
- git - 除了默认的所有分支的 Teamcity 分支规范
- linux - RStudio 错误“path.expand(path) 中的错误:'path' 参数无效;tmp/time.rds',可能的原因'没有这样的文件或目录”
- apache-kafka - Producer metric:record_error_rate,这个值什么时候会大于零
- database - 如何在 Flutter+Spring Boot+PostgreSQL+Heroku 结构中发送和存储图像?
- javascript - 将下载和解压缩进度混合为一个 TotalProgress
- c# - C#:通过引用将附加参数传递给委托
- c++ - 在我的类成员函数中,'operator>>' 不匹配,使用 set 和 get 读取文件输入
- powershell - 如何通过 csv 文件读取输入并将输出写入 power shell 脚本的输出文件?