Advertisement
Guest User

Untitled

a guest
Jun 9th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. #!/usr/bin/python3
  2. from urllib.request import urlopen, Request
  3. import urllib
  4. from bs4 import BeautifulSoup
  5. import time
  6. import pymysql.cursors
  7.  
  8.  
  9.  
  10. def lookup_amazon_price(prod_code):
  11.  url = 'http://www.amazon.com/dp/'+prod_code
  12.  req = urllib.request.Request(
  13.      url,
  14.      data=None,
  15.      headers={
  16.         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
  17.      }
  18.  )
  19.  
  20.  f = urllib.request.urlopen(req)
  21.  html = f.read().decode('utf-8')
  22.  bsObj = BeautifulSoup ( html , "lxml")
  23.  t = bsObj.find("span",{'id':'productTitle'})
  24.  p = bsObj.find("span",{'id':'priceblock_ourprice'})
  25.  title = t.get_text()
  26.  title = " ".join(title.split())
  27.  price = p.get_text()
  28.  all_item_info = [title,price]
  29.  return all_item_info
  30.  
  31. filename = 'tocheck.txt'
  32. with open(filename) as f:
  33.  lines = [line.rstrip('\n') for line in open(filename)]
  34.  
  35. num_prod = len(lines)
  36.  
  37. # Connect to the database
  38. connection = pymysql.connect(host='localhost',
  39.                              user='username',
  40.                              password='password',
  41.                              db='database',
  42.                              charset='utf8mb4',
  43.                              cursorclass=pymysql.cursors.DictCursor)
  44.  
  45. try:
  46.  with connection.cursor() as cursor:
  47.   # Create a new record
  48.   print('\nAmazon Price Logger:\nby Someone\n\nThere are '+str(num_prod)+' products to check:\n\nBeginning Now\n\n')
  49.   for prod_code in lines:
  50.    all_item_info = lookup_amazon_price(prod_code)
  51.    sql = 'INSERT INTO products (id_num, title) VALUES (%s, %s) ON DUPLICATE KEY UPDATE added=added'
  52.    cursor.execute(sql, (prod_code,all_item_info[0]))
  53.    connection.commit()
  54.    sql = 'INSERT INTO prices (id_num, price) VALUES (%s, %s) ON DUPLICATE KEY UPDATE time=time'
  55.    cursor.execute(sql, (prod_code,all_item_info[1]))
  56.    connection.commit()
  57.    num_prod -= 1
  58.    print('Product: '+all_item_info[0]+'\nPrice: '+all_item_info[1]+'\nProducts Remaining: '+str(num_prod)+'\n\n')
  59.    time.sleep(5)
  60.  
  61. finally:
  62.     connection.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement