ScrapTFRaffleBotSelenium/classes/browser.py

71 lines
2.3 KiB
Python

import undetected_chromedriver as uc
import time
import os
import sys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# from seleniumbase import Driver
from termcolor import colored
CHROMEDRIVER = "chromedriver"
class Browser():
def __init__(self, timeout=15):
chromedriver_path = os.path.join(
os.path.dirname(__file__) + '/../', CHROMEDRIVER)
if os.path.exists(chromedriver_path):
uc.install(
executable_path=chromedriver_path,
)
else:
print(colored(
f"Couldn't find a dedicated 'chromedriver'! Relying on an installed browser instead...", "yellow"))
options = uc.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
self.instance = uc.Chrome(use_subprocess=False, options=options, incognito=True)
# self.instance = Driver(uc=True, incognito=True)
self.timeout = timeout
self.instance.implicitly_wait(self.timeout)
def quit(self):
self.instance.quit()
def open(self, url):
self.instance.get(url)
def get_element(self, selector):
return self.instance.find_element(By.CSS_SELECTOR, selector)
def get_elements(self, selector):
return self.instance.find_elements(By.CSS_SELECTOR, selector)
def element_exists(self, selector):
try:
self.get_element(selector)
return True
except Exception:
return False
def click_element(self, selector):
try:
self.get_element(selector).click_safe()
return True
except Exception as e:
print(colored(f"Couldn't click on {'selector'}: {e}", "red"))
return False
def find_element(self, selector, text, visible=False):
try:
for element in self.get_element(selector):
if not visible or element.is_displayed():
return element
except Exception:
pass
return False
def add_cookie(self, key, value, cookie_domain, url):
self.instance.add_cookie({"name": key, "value": value, "domain": cookie_domain})
def scroll_down(self):
self.get_element('body').send_keys(Keys.END)