我编写了以下代码,但是,在我的输出中,我仅收到yelp id,对于每个检查列,我均将“ None”作为输出。为什么会发生这种情况?我的目标是通过Python打Yelp API来检索最新的3条评论。 我已经参考了文档:https://www.yelp.com/developers/documentation/v3/business_match
from __future__ import print_function
#import yelpSDK
import json
#from pandas import *
#import pdb
import pandas as pd
import datetime
#import geocoder
#from geopy.geocoders import Nominatim
import argparse
import json
import pprint
import requests
import sys
import urllib
# This client code can run on Python 2.x or 3.x. Your imports can be
# simpler if you only need one of those.
try:
# For Python 3.0 and later
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.parse import urlencode
except ImportError:
# Fall back to Python 2's urllib2 and urllib
from urllib2 import HTTPError
from urllib import quote
from urllib import urlencode
API_KEY = 'abc'
# API constants, you shouldn't have to change these.
API_HOST = 'https://api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/' # Business ID will come after slash.
BUSINESS_MATCHES_PATH = '/v3/businesses/matches'
BUSINESS_REVIEWS_PATH = '/v3/businesses/{id}/reviews'
# Defaults for our simple example.
DEFAULT_TERM = 'dinner'
DEFAULT_LOCATION = 'San Francisco, CA'
SEARCH_LIMIT = 3
def request(host, path, api_key, url_params=None):
"""Given your API_KEY, send a GET request to the API.
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
API_KEY (str): Your API Key.
url_params (dict): An optional set of query parameters in the request.
Returns:
dict: The JSON response from the request.
Raises:
HTTPError: An error occurs from the HTTP request.
"""
url_params = url_params or {}
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
headers = {
'Authorization': 'Bearer %s' % api_key,
}
print(u'Querying {0} ...'.format(url))
response = requests.request('GET', url, headers=headers, params=url_params)
return response.json()
def search_matches(api_key, business):
"""Query the Search API by a search term and location.
Args:
term (str): The search term passed to the API.
location (str): The search location passed to the API.
Returns:
dict: The JSON response from the request.
"""
url_params = {
'name': business['name'],#replace(' ', '+'),
'address1': business['address1'],#.replace(' ', '+'),
'city': business['city'],#.replace(' ', '+'),
'state': business['state'],#.replace(' ', '+'),
'zip_code': business['zip_code'],#.replace(' ', '+'),
'country': business['country']#.replace(' ', '+')
}
return request(API_HOST, BUSINESS_MATCHES_PATH, api_key, url_params=url_params)
def get_business(API_KEY, business_id):
"""Query the Business API by a business ID.
Args:
business_id (str): The ID of the business to query.
Returns:
dict: The JSON response from the request.
"""
business_path = BUSINESS_REVIEWS_PATH + business_id
return request(API_HOST, business_path, API_KEY)
def get_business_id(business):
#import pdb; pdb.set_trace()
try:
business_id = search_matches(API_KEY, business)
b_id = business_id['businesses'][0]['id']
except:
b_id = 'None'
return b_id
df=pd.read_csv("InsuredEVG_sample10.csv", encoding='cp1252')
df['zip_code']=df['zip_code'].apply(str)
df1 = df.to_dict(orient='record')
length = len(df1)
input_range = list(range(0, length))
def id_loop(df1):
empty = []
for i in input_range:
business_id = get_business_id(df1[i])
empty.append(business_id)
return empty
a = id_loop(df1)
def get_reviews(business_id):
review0 = []
review1 = []
review2 = []
for i in input_range:
business_detail = get_business(API_KEY,business_id[i])
try:
rev0 = business_detail['text']
except:
rev0 = 'None'
try:
rev1 = business_detail['text']
except:
rev1 = 'None'
try:
rev2 = business_detail['text']
except:
rev2 = 'None'
review0.append(rev0)
review1.append(rev1)
review2.append(rev2)
return review0, review1, review2
b = get_reviews(a)
df['rev0'] = b[0]
df['rev1'] = b[1]
df['rev2'] = b[2]
df.to_csv('InsuredEVG_sample10_Output_revs3.csv')