modified main.py with a new test case

This commit is contained in:
Shaghayegh
2023-04-14 09:19:29 +02:00
parent f56dc86e67
commit c61d4e6aee
21 changed files with 9163 additions and 2646 deletions
+3 -4
View File
@@ -14,9 +14,9 @@ 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()))
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()
@@ -25,7 +25,6 @@ class ScrapeWithSelenium:
self.urls = urls if urls else []
self.items = []
self.config = ConfigParser()
# I should pass this as argument
with codecs.open(os.getcwd() + config_xpath , 'r', encoding='utf-8') as f :
self.config.read_file(f)
self.run()
+72 -38
View File
@@ -1,64 +1,97 @@
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, ElementClickInterceptedException
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
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException, ElementClickInterceptedException, ElementNotInteractableException
class ProjectLinksSelenium:
def __init__(self, url, website_name, config_link, body_wait_time, xpath_wait_time):
self.config = ConfigParser()
self.url = url
def __init__(self, start_urls, website_name, config_link, body_wait_time, xpath_wait_time):
self.start_urls = start_urls
self.website_name = website_name
self.config_link = config_link
self.body_wait_time = body_wait_time
self.xpath_wait_time = xpath_wait_time
self.config_link = config_link
self.website_name = website_name
self.config.read(os.getcwd() + config_link)
self.links = []
self.isNextDisabeled = False
self.config = ConfigParser()
with codecs.open(os.getcwd() + config_link, 'r', 'utf-8') as f:
self.config.read_file(f)
self.options = webdriver.ChromeOptions()
self.options.add_argument('--headless')
self.options.add_argument('--disable-cookies')
self.options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=self.options)
self.driver.delete_all_cookies()
self.driver.get(self.url)
self.isNextDisabeled = False
self.project_links = []
self.links_config = self.config[self.website_name]
self.driver.get(self.start_urls)
self.driver.maximize_window()
self.extract_project_links()
def extract_project_links(self):
self.fill_out_search_form()
while not self.isNextDisabeled:
links_config = self.config[self.website_name]
def fill_out_search_form(self):
if 'search-box' in self.links_config and 'search-btn' in self.links_config:
try:
WebDriverWait(self.driver,self.body_wait_time).until(EC.presence_of_element_located((By.XPATH, links_config['loading-body'])))
container = self.driver.find_element(By.XPATH, links_config['projects-container'])
projects = container.find_elements(By.XPATH, links_config['projects-list'])
for project in projects:
try:
self.links.append(project.find_element(By.XPATH, links_config['project-link']).get_attribute("href"))
except StaleElementReferenceException as e:
logging.error(f"The reference to an element in the DOM is no longer valid: {e}")
continue
search_box = self.driver.find_element(By.XPATH, self.links_config['search-box'])
search_keyword = self.links_config['search-keyword']
if search_keyword:
search_box.send_keys(search_keyword)
else:
search_box.send_keys('Universität Duisburg-Essen')
try:
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, links_config['next-btn'])))
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.element_to_be_clickable((By.XPATH, links_config['next-btn'])))
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['search-btn'])))
search_button = self.driver.find_element(By.XPATH, self.links_config['search-btn'])
search_button.click()
except (TimeoutException, NoSuchElementException, ElementNotInteractableException ) as e:
logging.error(f'Timeout waiting for search button to be clickable: {e}')
return
try:
WebDriverWait(self.driver, self.body_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['loading-body'])))
except TimeoutException:
logging.error('Timeout waiting for page to load after clicking search button')
return
next_btn = self.driver.find_element(By.XPATH, links_config['next-btn'])
self.extract_project_links()
except (NoSuchElementException, ElementNotInteractableException) as e:
logging.error(f'Error finding the form elements: {e}')
else:
logging.info('No search form found in config file. Extracting project links...')
self.extract_project_links()
def extract_project_links(self):
while not self.isNextDisabeled:
try:
WebDriverWait(self.driver,self.body_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['loading-body'])))
container = self.driver.find_element(By.XPATH, self.links_config['projects-container'])
projects = container.find_elements(By.XPATH, self.links_config['projects-list'])
# Extracting project links from a webpage
for project in projects:
try:
self.project_links.append(project.find_element(By.XPATH, self.links_config['project-link']).get_attribute("href"))
except StaleElementReferenceException as e:
logging.error(f"The reference to the element in the DOM is no longer valid: {e}")
continue
# Pagination
try:
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['next-btn'])))
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.element_to_be_clickable((By.XPATH, self.links_config['next-btn'])))
next_btn = self.driver.find_element(By.XPATH, self.links_config['next-btn'])
next_btn_class = next_btn.get_attribute('class')
if links_config['next_disable_condition'] in next_btn_class:
if 'next_disable_condition' in self.links_config and self.links_config['next_disable_condition'] in next_btn_class:
self.isNextDisabeled = True
else:
self.driver.execute_script("arguments[0].click();", next_btn)
@@ -73,17 +106,18 @@ class ProjectLinksSelenium:
except ElementClickInterceptedException as e:
logging.error(f"Button not clickable: {e}")
self.isNextDisabeled = True
except (TimeoutException, StaleElementReferenceException) as e:
logging.error(f"Failed to locate project container: {e}")
self.isNextDisabeled = True
self.save_project_links()
self.save_project_links()
def save_project_links(self):
df_links = pd.DataFrame({'project_link':self.links})
df_links.to_json(f"project_links_{self.website_name}.json", orient='records')
self.driver.quit()
return self.links
df = pd.DataFrame(self.project_links, columns=['project_link'])
df.to_json(f'project_links_{self.website_name}.json', orient='records')