使用Python调用JSON API

7eumitmz  于 2023-04-28  发布在  Python
关注(0)|答案(7)|浏览(132)

该程序将提示输入位置,联系Web服务并检索Web服务的JSON并解析该数据,并从JSON中检索第一个place_id。地点ID是一个文本标识符,用于在GoogleMap中唯一标识一个地点。API端点
要完成此任务,您应该使用此API端点,该端点具有Google数据的静态子集:
http://py4e-data.dr-chuck.net/json-此API使用与Google API相同的参数(地址)。此API也没有速率限制,因此您可以随时测试。如果你访问的URL没有参数,你会得到“没有地址。..”回答。

我已经完成了这个任务,但代码没有运行。我是JSONDecodeError每当我运行程序。

import urllib.request, urllib.parse, urllib.error
import json
adr= 'http://py4e-data.dr-chuck.net/json?'
while True:
    loca= input('Enter Location: ')
    if len(loca)<1:break

    url=adr + urllib.parse.urlencode({"address": loca})
    print('Retrieving', url)
    fha=urllib.request.urlopen(url)
    data=fha.read().decode()
    print('Retrieved', len(data))

    jsdata=json.loads(str(data))
    placeid= jsdata['results'][0]['place_id']
    print('The Place ID is: ', placeid)
aemubtdh

aemubtdh1#

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

target = 'http://py4e-data.dr-chuck.net/json?' 
local = input('Enter location: ')
url = target + urllib.parse.urlencode({'address': local, 'key' : 42})

print('Retriving', url)
data = urllib.request.urlopen(url).read()
print('Retrived', len(data), 'characters')
js = json.loads(data)
print(json.dumps(js, indent = 4)) 
print('Place id', js['results'][0]['place_id'])
beq87vna

beq87vna2#

似乎错误在于这需要一个额外的参数(Key)

Missing/incorrect key = parameter (it is an easy number to guess) ...

编辑:检查文档https://www.py4e.com/code3/geodata/README.txt
示例1:http://py4e-data.dr-chuck.net/json?key=42&address=Monash+University
示例2:http://py4e-data.dr-chuck.net/json?key=42&address=Kokshetau+Institute+of+Economics+and+Management

laawzig2

laawzig23#

这是查询的最新代码

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


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


#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "South Federal University"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)
cbwuti44

cbwuti444#

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


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


#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "IIT KANPUR"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)
DATA URL:  http://py4e-data.dr-chuck.net/json?address=IIT+KANPUR&key=42
{'results': [{'access_points': [], 'address_components': [{'long_name': 'Kalyanpur', 'short_name': 'Kalyanpur', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'Kanpur', 'short_name': 'Kanpur', 'types': ['locality', 'political']}, {'long_name': 'Kanpur Nagar', 'short_name': 'Kanpur Nagar', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Uttar Pradesh', 'short_name': 'UP', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}, {'long_name': '208016', 'short_name': '208016', 'types': ['postal_code']}], 'formatted_address': 'Kalyanpur, Kanpur, Uttar Pradesh 208016, India', 'geometry': {'location': {'lat': 26.5123388, 'lng': 80.2329}, 'location_type': 'GEOMETRIC_CENTER', 'viewport': {'northeast': {'lat': 26.5136877802915, 'lng': 80.23424898029151}, 'southwest': {'lat': 26.5109898197085, 'lng': 80.23155101970849}}}, 'place_id': 'ChIJcb6oxAE3nDkRNoTDq4Do-zo', 'plus_code': {'compound_code': 'G66M+W5 Kalyanpur, jvs tower, Kanpur, Uttar Pradesh, India', 'global_code': '7MR2G66M+W5'}, 'types': ['establishment', 'point_of_interest', 'university']}], 'status': 'OK'}
PLACE ID:  ChIJcb6oxAE3nDkRNoTDq4Do-zo
r9f1avp5

r9f1avp55#

# In this program you will use a GeoLocation lookup API modelled after the
# Google API to look up some universities and parse the returned data.
import ssl
import urllib.request, urllib.parse, urllib.error
import json

api_key= False
# api_key='....'
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 certification
ctx=ssl.create_default_context()
ctx.check_hostname=False
ctx.verify_mode=ssl.CERT_NONE

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

    contents= dict()
    contents['address']=address
    if api_key is not False: contents['key']=api_key
    url= serviceurl+ urllib.parse.urlencode(contents)

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

    ## check--- working or not
    try:
        js= json.loads(data)
    except:
        None

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

    ## For proper representation
    print(json.dumps(js, indent=4))
    ## Print various values
    loc= js['results'][0]['place_id']
    print('Loc', loc)
    addr= js['results'][0]['formatted_address']
    print('Address of', address,'is:',addr)
    lati= js['results'][0]['geometry']['location']['lat']
    long= js['results'][0]['geometry']['location']['lng']
    print('Latitude:',lati,'\nLongitude:',long)
bkhjykvo

bkhjykvo6#

使用urllib从URL打开和收集数据。JSON来解析数据并在JavaScript中加载。我们会得到结果的,i。即使用placeid = js['results'][0]['place_id']的位置ID。

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

api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy___IDByT70'
# https://developers.google.com/maps/documentation/geocoding/intro

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

    parms = dict()
    parms['address'] = address
    if api_key is not False: parms['key'] = api_key
    url = serviceurl + urllib.parse.urlencode(parms)

    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

    placeid = js['results'][0]['place_id']

    print('Place id', placeid)
rmbxnbpk

rmbxnbpk7#

你无法让程序工作的原因是因为你丢失了密钥,当你运行程序时,他们说它:缺少/不正确的键=参数(这是一个很容易猜到的数字)。..
我猜他们开玩笑说的是42岁,在银河系搭车指南中,这是生命的意义。

相关问题