Skip to content

Instantly share code, notes, and snippets.

@eristoddle
Created September 19, 2012 17:43
Show Gist options
  • Save eristoddle/3751029 to your computer and use it in GitHub Desktop.
Save eristoddle/3751029 to your computer and use it in GitHub Desktop.
Python Google Base Price Check
import urllib, json, operator, webbrowser, uuid
class gBasePriceReport():
"""
To Run Competition check leave keywords as None
To Run A Report to find pricing we don't have, leave store_name=None
and add keywords as a list of words expected[i.e. primeline, andersen, window]
"""
def __init__(self, api_key, store_name=None, keywords=None, sku_file=None):
self.api_key = api_key
self.store_name = store_name
self.keywords = keywords
self.sku_file = sku_file
def parse_base_result(self, g_base_json):
#TODO: This may have more than one page of results: in r_dict.count
try:
json_dict = json.loads(g_base_json)
r_dict = {"count" : json_dict['currentItemCount']}
listings = []
for i in json_dict['items']:
listing = {}
listing['title'] = i['product']['title']
if 'description' in i['product']:
listing['description'] = i['product']['description']
if 'brand' in i['product']:
listing['brand'] = i['product']['brand']
#if 'gtin' in i['product']:
#listing['gtin'] = i['product']['gtin']
listing['store'] = i['product']['author']['name']
if "images" in i['product']:
listing['image'] = i['product']['images'][0]['link']
listing['price'] = i['product']['inventories'][0]['price']
listings.append(listing)
r_dict['listings'] = listings
return r_dict
except Exception as e:
print "Error:",e
try:
return json_dict
except:
return None
def query_google_base(self, base_query):
try:
params = urllib.urlencode({'key': self.api_key,
'country': "US",
'q': base_query,
'alt': "json"})
f = urllib.urlopen("https://www.googleapis.com/shopping/search/v1/public/products?%s" % params)
return f.read()
except:
return "Error"
def batch_process_sku_file(self):
for line in open(self.sku_file, 'r'):
query = line.strip().replace('"', '')
yield query, self.parse_base_result(self.query_google_base(self.api_key, query))
def filter_to_competition(self, result):
if 'listings' in result:
for l in result['listings']:
if l['store'] == self.store_name:
return result['listings']
def filter_by_keywords(self, result):
if 'listings' in result:
for l in result['listings']:
print l
for k in self.keywords:
if k in l['title']:
return result['listings']
if 'description' in l:
if k in l['description']:
return result['listings']
def filter_each_by_keywords(self, result):
if result != None:
if 'listings' in result:
for l in result['listings']:
#print l
for k in self.keywords:
if k in l['title']:
yield l
if 'description' in l:
if k in l['description']:
yield l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment