import json from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import time from google.cloud import pubsub_v1 import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "C:/Users/Karen/AppData/Roaming/gcloud/application_default_credentials.json" options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(options=options) # Set up Pub/Sub subscription project_id = "fp-20230425" subscription_name = "fp-subscription-zipcodes" subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path(project_id, subscription_name) def callback(message): try: # Get the zip code from the message zip_code = message.data.decode('utf-8') print(f"Received zip code: {zip_code}") # Load the webpage with the zip code url = 'https://www.sayweee.com/en/product/Want-Want-Senbei-Rice-Crackers/17119' driver.get(url) driver.find_element(By.XPATH, '/html/body/div[4]/div/div[2]/div/div[2]/div[2]/div/div[1]/form/div/div/div[1]/div/div/div[2]/input').send_keys(zip_code) driver.find_element(By.XPATH, '/html/body/div[4]/div/div[2]/div/div[2]/div[2]/div/div[1]/form/div/div/div[1]/div/div/div[3]/div').click() # Extract the price from the webpage next_data_element = driver.find_element(By.XPATH, "//script[@type='application/ld+json']") next_data_text = next_data_element.get_attribute('innerHTML') next_data_start_index = next_data_text.index('{') next_data_end_index = next_data_text.rindex('}') + 1 next_data_json = next_data_text[next_data_start_index:next_data_end_index] next_data = json.loads(next_data_json) price = next_data['offers']['price'] # Print the result print(f"Price of rice crackers in zip code {zip_code}: {price}") except Exception as e: print(f"Error processing message: {str(e)}") finally: message.ack() subscriber.subscribe(subscription_path, callback=callback) while True: time.sleep(1)