from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException, WebDriverException from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import logging from configparser import ConfigParser import codecs import os import pandas as pd class ScrapeWithSelenium: def __init__(self, urls, body_wait_time, xpath_wait_time, config_xpath, website_name): self.options = webdriver.ChromeOptions() self.options.add_argument('--headless') self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=self.options) self.config_xpath = config_xpath self.website_name = website_name self.driver.maximize_window() self.body_wait_time=body_wait_time self.xpath_wait_time=xpath_wait_time self.urls = urls if urls else [] self.items = [] self.config = ConfigParser() with codecs.open(os.getcwd() + config_xpath , 'r', encoding='utf-8') as f : self.config.read_file(f) self.run() def scrape(self, url): self.driver.get(url) item = {} try: WebDriverWait(self.driver, self.body_wait_time).until(EC.presence_of_all_elements_located((By.XPATH, "//body"))) except TimeoutException as e: logging.error(f"TimeoutException: {e}. Unable to load the page at URL: {url}") return None except WebDriverException as e: logging.error(f"WebDriverException: {e}") return None for field_name, xpath in self.config.items('fields'): try: WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, xpath))) except NoSuchElementException as e: logging.error(f"NoSuchElementException: {e}. Unable to find element with xpath {xpath} on page: {url}") item[field_name] = "" continue except StaleElementReferenceException as e: logging.error(f"StaleElementReferenceException: {e}. The element with XPATH {xpath} is no longer attached to the DOM on page: {url}") item[field_name] = "" continue except TimeoutException as e: logging.error(f"TimeoutException: {e}. Unable to load the xpath {xpath} at URL: {url}") item[field_name] = "" continue output_list = self.driver.find_elements(By.XPATH, xpath) if len(output_list) == 1: href = output_list[0].get_attribute('href') item[field_name] = href if href is not None else output_list[0].text else: item[field_name] = [output.get_attribute('href') if output.get_attribute('href') is not None else output.text for output in output_list] return item def run(self): for url in self.urls: result = self.scrape(url) if result: self.items.append(result) df = pd.DataFrame(self.items) df.to_json(f"scraped_data_{self.website_name}.json", orient='records', force_ascii=False) self.driver.quit()