Last active
March 22, 2019 02:51
-
-
Save dhruvkar/0b838489fd027f3011d000ae2390fc01 to your computer and use it in GitHub Desktop.
Get Yelp and Google ratings of a business, given the business name, address, & phone number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import json | |
import re | |
import requests # pip install requests | |
from yelpapi import YelpAPI # pip install yelpapi. Not a very mature library, use at your own risk. | |
from requests.compat import urljoin, quote_plus | |
# API KEYS | |
YELP_CLIENT_ID = "" # sign up at https://www.yelp.com/developers and create an app. | |
YELP_CLIENT_SECRET = "" # same as above | |
GOOGLE_API_KEY = "" # sign up at https://console.developers.google.com and enable | |
# "Google Places API Web Service" & "Google Maps Geocoding API" | |
# API ENDPOINTS | |
GEOCODE_URL = "https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}" | |
PLACENEARBY_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={0}&radius=500&type=contractor&keyword={1}&key={2}" | |
################### | |
# UTILITY METHODS | |
################### | |
def _clean_phone(raw_phone): | |
""" | |
Given a raw US phone number, remove dashes, parentheses and spaces | |
and add in a '+1' at the start to use with Yelp API | |
""" | |
phone = str(raw_phone) | |
phone = raw_phone.replace(" ", "") | |
phone = phone.replace("-", "") | |
phone = phone.replace("(", "") | |
phone = phone.replace(")", "") | |
if len(phone) == 10: | |
phone = "+1" + phone | |
return phone | |
def _merge_dicts(*dict_args): | |
""" | |
Given any number of dicts, shallow copy and merge into a new dict, | |
precedence goes to key value pairs in latter dicts. | |
""" | |
result = {} | |
for dictionary in dict_args: | |
result.update(dictionary) | |
return result | |
#################### | |
# RATINGS METHODS | |
#################### | |
def google_rating(business_name, address, key=GOOGLE_API_KEY, gcurl=GEOCODE_URL, pnurl=PLACENEARBY_URL): | |
""" | |
Given a business name and address, get Google ratings from the Places API. | |
Address is geocoded first to get latitute, longitude. | |
Tries to narrow down to a specific business. | |
""" | |
geocode = gcurl.format(quote_plus(address), key) | |
r = requests.get(geocode) | |
if r.ok: | |
raw_loc = json.loads(r.content)['results'][0]['geometry']['location'] | |
usable_loc = ",".join((str(raw_loc['lat']), str(raw_loc['lng']))) | |
placenearby = pnurl.format(usable_loc, quote_plus(business_name), key) | |
r = requests.get(placenearby) | |
if r.ok: | |
placeinfo = json.loads(r.content) | |
rating = placeinfo['results'][0]['rating'] # assumes first result in list is correct | |
return {"google_rating": rating} | |
else: | |
print ("Somthing went wrong with places nearby search. Status Code: ", r.status_code) | |
return {"google_rating": None} | |
else: | |
print ("Something went wrong with geocoding request. Status Code: ", r.status_code) | |
return {"google_rating": None} | |
def yelp_rating(cid=YELP_CLIENT_ID, cs=YELP_CLIENT_SECRET, **kwargs): | |
""" | |
Given a phone or business_id, get Yelp ratings for a business. | |
Business needs to have at least one rating to return. | |
Using phone number not reliable, so main uses Business ID | |
Uses Yelp Fusion API (v3). | |
""" | |
y = YelpAPI(cid, cs) | |
if kwargs.get("phone"): | |
try: | |
res = y.phone_search_query(phone=_clean_phone(kwargs.get("phone"))) | |
if len(res['businesses']) == 1: | |
rating = res['businesses'][0]['rating'] | |
reviews = res['businesses'][0]['review_count'] | |
return {"yelp_rating":rating, "yelp_reviews": reviews} | |
elif len(res['businesses']) == 0: | |
print ("no business found with that phone number") | |
return {"yelp_rating": None, "yelp_reviews": None} | |
else: | |
print ("multiple businesses found for phone") | |
return {"yelp_rating": "Multiple", "yelp_reviews": "Multiple"} | |
except Exception as e: | |
print (e) | |
elif kwargs.get("business_id"): | |
try: | |
res = y.business_query(id=kwargs.get("business_id")) | |
rating = res['rating'] | |
reviews = res['review_count'] | |
return {"yelp_rating":rating, "yelp_reviews": reviews} | |
except Exception as e: | |
print (e) | |
return {"yelp_rating": None, "yelp_reviews": None} | |
else: | |
print ("supply a 'business_id' or 'phone' for business to search yelp") | |
############# | |
# MAIN METHOD | |
############## | |
def main(business_name, address, yelp_business_id=""): | |
""" | |
Uses Business ID rather than phone number as it was more reliable in testing. | |
Will only return Google ratings if Yelp business ID not supplied. | |
""" | |
google = google_rating(business_name=business_name, address=address) | |
if yelp_business_id: | |
yelp = yelp_rating(business_id=yelp_business_id) | |
return _merge_dicts(yelp, google) | |
else: | |
return google |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment