75 lines
3.0 KiB
Python
75 lines
3.0 KiB
Python
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):
|
|
# self.options = webdriver.ChromeOptions()
|
|
# self.options.add_argument('--headless')
|
|
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
|
|
self.driver.maximize_window()
|
|
self.urls = urls if urls else []
|
|
self.items = []
|
|
self.config = ConfigParser()
|
|
with codecs.open(os.getcwd() + './Bachelorarbeit/EU_xpath_config.ini', '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, 10).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, 1).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:
|
|
item[field_name] = output_list[0].text
|
|
else:
|
|
item[field_name] = [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(self.config['EU']['data_set'], orient='records', force_ascii=False)
|
|
self.driver.quit() |