""" Check the Amazon PS5 Stock using a simple GET Request. """ __author__ = "Lukas Mahler" __version__ = "0.1.0" __date__ = "13.08.2021" __email__ = "m@hler.eu" __status__ = "Development" # Imports import os import sys import random import dotenv import logging import requests import traceback from time import sleep from bs4 import BeautifulSoup from datetime import datetime from logging.handlers import TimedRotatingFileHandler # Constants DEBUG = False CRON = False TEST = True URL = 'https://www.amazon.de/Sony-Interactive-Entertainment-PlayStation-5/dp/B08H93ZRK9' def getStock(): headers = { 'DNT': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36' } with requests.Session() as s: s.headers = headers s.trust_env = False site = s.get(URL) if site.status_code != 200: print(f"Fehler: HTTP-Statuscode {site.status_code} <> 200") exit() soup = BeautifulSoup(site.content, 'lxml') span = soup.find("span", class_="a-size-medium a-color-price").text avail = span.strip() if DEBUG: print(f"DEBUG: avail = [{avail}]") if avail == "Derzeit nicht verfügbar.": status = 'Out of Stock' else: status = 'In Stock' return status def reportError(etype, evalue, tbobj): # Hacky find the last error line number lasttb = traceback.format_tb(tbobj)[-1] start = lasttb.find('line ') end = lasttb.find(', in', start) lastlno = lasttb[start:end] # tb = ''.join(traceback.format_exception(etype, evalue, tbobj)) txt = str(lastlno) + " - " + str(etype) + " - " + str(evalue) mylog.error(txt) # mylog.error(tb) def initLogger(): global mylog # now = date.today().strftime("%Y-%m-%d") mylog = logging.getLogger() mylog.setLevel(logging.INFO) # handler = logging.FileHandler(f'ps5amazon_{now}_v{__version__}.log', 'a', 'utf-8') fname = f'ps5amazon_v{__version__}.log' handler = TimedRotatingFileHandler(filename=fname, when='D', interval=1, backupCount=14, encoding='utf-8', delay=False) formatter = logging.Formatter('%(asctime)s - %(levelname)7s - %(message)s') handler.setFormatter(formatter) mylog.addHandler(handler) def main(): # error handling sys.excepthook = reportError initLogger() dotenv_file = dotenv.find_dotenv() if not dotenv_file: # either open(".env", 'x').close() dotenv_file = dotenv.find_dotenv() # or # raise FileNotFoundError("could not locate .env file") dotenv.load_dotenv(dotenv_file) dotend_keys = dotenv.dotenv_values() if not {"STOCKSTATUS"} <= dotend_keys.keys(): # either dotenv.set_key(dotenv_file, "STOCKSTATUS", "") # or # raise ValueError("missing key in your .env file.") """ Given the script executes as Cronjob add a random sleep timer. This will make our Request appear less botty """ if CRON: sleep(random.randint(1, 30)) stock_status = getStock() if stock_status != os.getenv("STOCKSTATUS"): if TEST: now = datetime.now().strftime("%Y-%m-%d-%H.%M") + "-" + stock_status open(now, 'x').close() dotenv.set_key(dotenv_file, "STOCKSTATUS", stock_status) else: pass if __name__ == "__main__": main()