def __init__(self, json_config): """Creates and starts firefox in kiosk mode on main display""" # config[KIOSK] is loaded here self.config = json_config # Load launch arguments self.options = ChromeOptions() # Load user data folder if 'keep_data' is set in config (This is default behavior) if KIOSK_KEEP_DATA in self.config and self.config[ KIOSK_KEEP_DATA] is True: KIOSK_LAUNCH_ARGUMENTS.append(KIOSK_USER_DIR_ARG + self.home_folder + KIOSK_USER_DIR) # Add all launch arguments for arg in KIOSK_LAUNCH_ARGUMENTS: self.options.add_argument(arg) # Disables remote control warning self.options.add_experimental_option("excludeSwitches", ['enable-automation']) self.options.add_experimental_option('useAutomationExtension', False) # Create driver self.browser = webdriver.Chrome(options=self.options) self.open_page(self.config[KIOSK_URL]) self.homepage = self.browser.window_handles
def setUpClass(cls): call_command('migrate', verbosity=0) cls.profile = fake.simple_profile() cls.profile['password'] = fake.password() super(SeleniumTestCase, cls).setUpClass() # Default to using firefox for selenium testing, if not try Chrome try: os.environ['MOZ_HEADLESS'] = '1' options = FirefoxOptions() options.add_argument('-headless') cls.driver = webdriver.Firefox(firefox_options=options) except WebDriverException: options = ChromeOptions() if os.environ.get('GOOGLE_CHROME_BINARY', None): options.binary_location = \ os.environ['GOOGLE_CHROME_BINARY'] options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument('--no-sandbox') options.add_argument('--log-level=3') options.add_argument('--window-size=1280,720') cls.driver = webdriver.Chrome(chrome_options=options) cls.driver.implicitly_wait(10) cls.wait_time = 5
def connectChrome(): options = ChromeOptions() options.add_argument("--headless") chromeDriverPath = "/usr/local/bin/chromedriver" driver = webdriver.Chrome(chromeDriverPath, chrome_options=options) print("Chrome Headless Browser Invoked - Friday Video Lottery v0.1b") return driver
def set_driver_for_browser(self, browser_name): """expects browser name and returns a driver instance""" # if browser is suppose to be chrome if browser_name.lower() == "chrome": browser_option = ChromeOptions() # automatically installs chromedriver and initialize it and returns the instance if self.proxy is not None: options = { 'https': 'https://{}'.format(self.proxy.replace(" ", "")), 'http': 'http://{}'.format(self.proxy.replace(" ", "")), 'no_proxy': 'localhost, 127.0.0.1' } print("Using: {}".format(self.proxy)) return webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=self.set_properties(browser_option), seleniumwire_options=options) return webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=self.set_properties(browser_option)) elif browser_name.lower() == "firefox": browser_option = FirefoxOptions() if self.proxy is not None: options = { 'https': 'https://{}'.format(self.proxy.replace(" ", "")), 'http': 'http://{}'.format(self.proxy.replace(" ", "")), 'no_proxy': 'localhost, 127.0.0.1' } print("Using: {}".format(self.proxy)) return webdriver.Firefox(executable_path=GeckoDriverManager().install(), options=self.set_properties(browser_option), seleniumwire_options=options) # automatically installs geckodriver and initialize it and returns the instance return webdriver.Firefox(executable_path=GeckoDriverManager().install(), options=self.set_properties(browser_option)) else: # if browser_name is not chrome neither firefox than raise an exception raise Exception("Browser not supported!")
def setUp(self): # test with Firefox, without headless() # self.driver = Firefox(executable_path='/opt/WebDriver/bin/geckodriver') # test with Firefox, with headless() # options = FirefoxOptions() # options.headless = True # options.headless = False # self.driver = Firefox(executable_path='/opt/WebDriver/bin/geckodriver', options=options) # test with chrome, without headless() # self.driver = Chrome('/opt/WebDriver/bin/chromedriver') # test with chrome, with headless() options = ChromeOptions() options.headless = True # options.headless = False path_local = '/opt/WebDriver/bin/chromedriver' path_github_actions = '/home/runner/work/slate-portal/slate-portal/chromedriver' self.driver = Chrome(executable_path=path_github_actions, options=options) # portal on minislate self.driver.get('http://localhost:5000/slate_portal') # slate portal # self.driver.get('https://portal.slateci.io/slate_portal') self.driver.set_window_size(1920, 1080)
def get_english(arg): '''한글을 받아서 파파고번역사이트에서 영어로 번역해서 리턴합니다''' rtn_str = "" try: chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None) if chrome_bin is not None: opts = ChromeOptions() opts.binary_location = chrome_bin opts.add_argument('headless') opts.add_argument("lang=ko_KR") opts.add_argument('--disable-gpu') opts.add_argument('--no-sandbox') browser = webdriver.Chrome(executable_path="chromedriver", chrome_options=opts) else: browser = webdriver.Chrome(LOCAL_DRIVER_URL) browser.implicitly_wait(3) browser.get(PAPAGO_URL) txt_source = browser.find_element_by_id('txtSource') txt_source.send_keys(arg) txt_source.send_keys(Keys.RETURN) time.sleep(5) txt_target = browser.find_element_by_id('txtTarget') rtn_str = txt_target.text finally: browser.quit() return rtn_str
def login(user, password): print('Starting the browser...') options = ChromeOptions() options.add_argument("--headless") driver = webdriver.Chrome(options=options) logging.basicConfig(stream=sys.stdout, level=logging.INFO) # driver = webdriver.Chrome() print( 'Browser started successfully. Navigating to the demo page to login.') driver.get('https://www.saucedemo.com/') logging.info('Loging in to https://www.saucedemo.com/') driver.find_element_by_css_selector( 'input[data-test="username"]').send_keys(user) driver.find_element_by_css_selector( 'input[data-test="password"]').send_keys(password) driver.find_element_by_css_selector('input[value=LOGIN]').click() logging.info('Searching for Products') headerLabel = driver.find_element_by_class_name('product_label').text assert "Products" in headerLabel logging.info('Successfully logged in, user: '******'Find products') products = driver.find_elements_by_css_selector('.inventory_item') logging.info('Add products to cart') for product in products: product_name = product.find_element_by_css_selector( '.inventory_item_name').text product.find_element_by_css_selector('button.btn_inventory').click() logging.info('Product added to cart: ' + product_name) logging.info('Verify if cart has 6 added products') cart_label = driver.find_element_by_css_selector( '.shopping_cart_badge').text assert cart_label == '6' logging.info('Navigate to cart') driver.find_element_by_css_selector('a.shopping_cart_link').click() assert '/cart.html' in driver.current_url, 'Cart navigation unsuccessful' logging.info('Removing products from cart') cart_products = driver.find_elements_by_css_selector('.cart_item') for product in cart_products: product_name = product.find_element_by_css_selector( '.inventory_item_name').text product.find_element_by_css_selector('button.cart_button').click() logging.info('Removed from cart: ' + product_name) logging.info('Verify if cart is empty') if driver.find_elements_by_css_selector('.shopping_cart_badge'): logging.info('Cart is empty') cart_state = 1 else: cart_state = 0 logging.info('Cart state: ' + str(cart_state)) assert cart_state == 0
def launch_chrome_driver(): logger.debug("loading chromedriver...") options = ChromeOptions() options.headless = headless if container: options.add_argument("--no-sandbox") return Chrome(options=options)
def run(self): # Options to run selenium via buildpacks on heroku chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None) opts = ChromeOptions() opts.binary_location = chrome_bin self.driver = webdriver.Chrome(executable_path="chromedriver", chrome_options=opts) self.valid_districts = [ "Engineering District 3-0", "Engineering District 4-0", "Engineering District 5-0", "Engineering District 6-0", "Engineering District 8-0" ] # Districts for the Pittsburgh office aren't always included self.valid_districts += [ "Engineering District 1-0", "Engineering District 2-0", "Engineering District 9-0", "Engineering District 10-0", "Engineering District 11-0", "Engineering District 12-0" ] self.base_url = "https://www.dot14.state.pa.us/ECMS" projects_by_district = {} project_and_rankings_list = [] self.login_user() project_list = self.collect_projects() for district in self.valid_districts: projects_by_district[district] = {} if type(project_list) == list: for job in project_list: # add project to the correct district project_and_rankings = { job['prono']: self.get_project_rankings(job) } projects_by_district[job['district']].update( project_and_rankings) self.driver.quit()
def __init__(self, driver_path: str = None, waiter_timeout: int = 3, options: List[str] = None): """Base class to WebScrapper with selenium :param driver_path: web drive file path :type: str :tip: if driver_path is none, FireFox web drive will be used :param waiter_timeout: general wait timeout :type: int :param options: driver config :type: List[str] """ # selecting driver if not driver_path: driver = webdriver.Firefox driver_options = FireFoxOptions() else: driver = webdriver.Chrome driver_options = ChromeOptions() # add config if options: for option in options: driver_options.add_argument(option) self.driver = driver(driver_path, options=driver_options) self.waiter = WebDriverWait(self.driver, waiter_timeout)
def __init__(self, base_url): base_url = self.base_url chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None) opts = ChromeOptions() opts.binary_location = chrome_bin self.driver = webdriver.Chrome(executable_path="chromedriver", chrome_options=opts)
def test_always_match_if_2_of_the_same_options(): from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.chrome.options import Options as ChromeOptions2 co1 = ChromeOptions() co1.add_argument("foo") co2 = ChromeOptions2() co2.add_argument("bar") expected = { "capabilities": { "alwaysMatch": { "browserName": "chrome", "pageLoadStrategy": "normal", }, "firstMatch": [ { "goog:chromeOptions": { "args": ["foo"], "extensions": [] } }, { "goog:chromeOptions": { "args": ["bar"], "extensions": [] } }, ] } } result = webdriver.create_matches([co1, co2]) assert expected == result
def test_first_match_when_2_different_option_types(): from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.firefox.options import Options as FirefoxOptions expected = { "capabilities": { "alwaysMatch": { "pageLoadStrategy": "normal" }, "firstMatch": [{ "browserName": "chrome", "goog:chromeOptions": { "extensions": [], "args": [] } }, { "browserName": "firefox", "acceptInsecureCerts": True, "moz:debuggerAddress": True, "moz:firefoxOptions": { "args": ["foo"] } }] } } result = webdriver.create_matches([ChromeOptions(), FirefoxOptions()]) assert expected == result
def init_driver(driver_path, browser_name): '''init the driver''' def set_properties(browser_option): '''sets the driver's properties''' ua = Headers().generate() #fake user agent browser_option.add_argument('--headless') browser_option.add_argument('--disable-extensions') browser_option.add_argument('--incognito') browser_option.add_argument('--disable-gpu') browser_option.add_argument('--log-level=3') browser_option.add_argument(f'user-agent={ua}') browser_option.add_argument('--disable-notifications') browser_option.add_argument('--disable-popup-blocking') return browser_option try: browser_name = browser_name.strip().title() #automating and opening URL in headless browser if browser_name == "Chrome": browser_option = ChromeOptions() browser_option = set_properties(browser_option) driver = webdriver.Chrome(driver_path, options=browser_option) elif browser_name == "Firefox": browser_option = FirefoxOptions() browser_option = set_properties(browser_option) driver = webdriver.Firefox(executable_path=driver_path, options=browser_option) else: driver = "Browser Not Supported!" return driver except Exception as ex: print(ex)
def browser(config_browser, config_headless_mode, request): if config_browser == 'chrome': options = ChromeOptions() options.headless = config_headless_mode options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') # mobile_emulation = {"deviceName": "Nexus 5"} # options.add_experimental_option("mobileEmulation", mobile_emulation) driver = Chrome(options=options) elif config_browser == 'firefox': options = FirefoxOptions() options.headless = config_headless_mode options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') driver = Firefox(options=options) elif config_browser == 'ie': if config_headless_mode: Warning("Headless mode is not supported in IE") driver = Ie() else: raise Exception(f'"{config_browser}" is not a supported browser') driver.delete_all_cookies() driver.set_window_size(1920, 1080) driver.implicitly_wait(wait_time) # Return the driver object at the end of setup yield driver # For cleanup, quit the driver driver.quit()
def initialize_driver(is_chrome, is_windows, is_headless=True): if is_chrome: opts = ChromeOptions() # Disable images from loaded pages prefs = {"profile.managed_default_content_settings.images": 2} opts.add_experimental_option("prefs", prefs) driver_name = "chromedriver" else: opts = FirefoxOptions() driver_name = "geckodriver" if is_headless: opts.add_argument("--headless") opts.add_argument("--width=1920") opts.add_argument("--height=1080") driver_suffix = ".exe" if is_windows else "" driver_path = os.path.join(os.getcwd(), driver_name + driver_suffix) if is_chrome: driver = webdriver.Chrome(options=opts, executable_path=driver_path) else: driver = webdriver.Firefox(options=opts, executable_path=driver_path) return driver
def __init__(self, headless=True, window_size='1920,1080', additional_options=(), timeout=3, browser_type='chrome'): if browser_type == 'firefox': options = FirefoxOptions() options.headless = headless self.driver = webdriver.Firefox(options=options) if window_size: self.driver.set_window_size( *[int(token) for token in window_size.split(',')]) else: options = ChromeOptions() options.headless = headless if window_size: options.add_argument(f'--window-size={window_size}') for o in additional_options: options.add_argument(o) options.add_argument('--ignore-certificate-errors') options.add_argument('disable-infobars') options.add_argument('--disable-notifications') options.add_argument('--no-sandbox') options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) options.add_experimental_option("prefs", {"enable_do_not_track": True}) self.driver = webdriver.Chrome(options=options) self.timeout = timeout self.driver.implicitly_wait(self.timeout)
def get_local_driver(browser=DEFAULT_BROWSER, headless=False) -> WebDriver: browser = get_local_browser(browser) if browser not in VALID_LOCAL_BROWSERS: raise AssertionError( f"{browser} not in VALID_LOCAL_BROWSERS ({VALID_LOCAL_BROWSERS})") driver_to_class = { "CHROME": webdriver.Chrome, "FIREFOX": webdriver.Firefox, "OPERA": webdriver.Opera, "PHANTOMJS": webdriver.PhantomJS, } driver_class = driver_to_class[browser] if browser == 'CHROME': options = ChromeOptions() if headless: options.add_argument('--headless') prefs = {'download.default_directory': DEFAULT_DOWNLOAD_PATH} options.add_experimental_option('prefs', prefs) return driver_class( desired_capabilities={"loggingPrefs": LOGGING_PREFS}, chrome_options=options) elif browser == 'FIREFOX': fp = webdriver.FirefoxProfile() fp.set_preference('network.proxy.type', 2) fp.set_preference('network.proxy.autoconfig_url', "http://127.0.0.1:9675") fp.set_preference('browser.download.folderList', 2) fp.set_preference('browser.download.dir', DEFAULT_DOWNLOAD_PATH) fp.set_preference("browser.helperApps.neverAsk.saveToDisk", 'application/octet-stream') return driver_class(firefox_profile=fp) else: return driver_class( desired_capabilities={"loggingPrefs": LOGGING_PREFS})
def login(user, password): print(timestamp() + 'Starting the browser...') # --uncomment when running in Azure DevOps. options = ChromeOptions() options.add_argument("--headless") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") driver = webdriver.Chrome(options=options) #driver = webdriver.Chrome() print( timestamp() + 'Browser started successfully. Navigating to the demo page to login.') driver.get('https://www.saucedemo.com/') # login print(timestamp() + 'Try to login in with {} {}'.format(user, password)) driver.find_element_by_css_selector("input[id='user-name']").send_keys( user) driver.find_element_by_css_selector("input[id='password']").send_keys( password) driver.find_element_by_id("login-button").click() # login test product_text = driver.find_element_by_css_selector( "div[id='header_container'] > div.header_secondary_container > span" ).text assert "PRODUCTS" in product_text print(timestamp() + 'Succesfull login in with {} {}'.format(user, password)) return driver
def __start_web_driver(self): """ Start the web driver """ driver_options = ChromeOptions() driver_options.add_experimental_option('excludeSwitches', ['enable-logging']) driver_options.add_argument('--mute-audio') driver_options.add_argument( '--user-agent=Mozilla/5.0 Chrome/74.0.3729.169 Safari/537.36') driver_options.headless = not self.__headful try: driver = webdriver.Chrome(service_log_path=os.devnull, options=driver_options) except SessionNotCreatedException as err: logger.error(err) print('could not start session') self.stop() except WebDriverException as err: logger.error('Launch Google Chrome error: %s' % err) print('could not launch Google Chrome: ') print('make sure Google Chrome is installed on your machine') self.stop() else: driver.maximize_window() driver.set_page_load_timeout(600) return driver
def __init__(self, username, login_user, login_pass, driver): self.username = username self.login_user = login_user self.login_pass = login_pass self.driver = driver # Use driver dependng on the chosen solution. # Driver has to be in PATH if self.driver == 'chromedriver': # Desde mediados de agosto los mamones de IG # detectan que estás conectado con Chromedriver o # con geckodriver. Incluimos la opción headless # para que no nos detecten. # Ver https://duo.com/decipher/driving-headless-chrome-with-python chrome_options = ChromeOptions() chrome_options.add_argument("--headless") # Uncomment for Heroku deployment. # chrome_options.binary_location = os.environ.get('GOOGLE_CHROME_BIN') # chrome_options.add_argument('--disable-gpu') # chrome_options.add_argument('--disable-dev-shm-usage') # chrome_options.add_argument('--no-sandbox') # self.browser = webdriver.Chrome(executable_path=os.environ.get('CHROMEDRIVER_PATH'), # chrome_options=chrome_options) # Commment for Heroku deploy self.browser = webdriver.Chrome(chrome_options=chrome_options) elif self.driver == 'geckodriver': # https://www.edureka.co/community/10026/headless-gecko-driver-using-selenium firefox_options = FirefoxOptions() firefox_options.add_argument("--headless") self.browser = webdriver.Firefox(firefox_options=firefox_options) self.url = "https://www.instagram.com/" + str(self.username)
def chrome_manager(self): opts = ChromeOptions() if self.on_travis: # github.com/travis-ci/travis-ci/issues/938 opts.add_argument("--no-sandbox") opts.add_argument("--load-extension=" + self.extension_path) opts.binary_location = self.browser_path opts.add_experimental_option( "prefs", {"profile.block_third_party_cookies": False}) caps = DesiredCapabilities.CHROME.copy() caps['loggingPrefs'] = {'browser': 'ALL'} for i in range(5): try: driver = webdriver.Chrome(options=opts, desired_capabilities=caps) except WebDriverException as e: if i == 0: print("") print("Chrome WebDriver initialization failed:") print(str(e) + "Retrying ...") else: break try: yield driver finally: driver.quit()
def check_login_page_by_language(self, language): if onusing_browser == "1": firefoxProfile = FirefoxProfile() firefoxProfile.set_preference("intl.accept_languages", language) self.driver = webdriver.Firefox(firefox_profile=firefoxProfile) elif onusing_browser == "2": options = ChromeOptions() options.add_argument("--lang=" + language) options.add_argument("--window-size=1920,1080") self.driver = webdriver.Chrome(chrome_options=options) elif onusing_browser == "3": self.assertTrue(False, " Do not use IE, Cannot set IE browser language") else: print "We don't support other browsers currently." self.driver.get(url_login) self.driver.implicitly_wait(15) self.check_login_page_UI_by_language(language) time.sleep(3) self.driver.close() time.sleep(1) if self.driver and onusing_browser != "1": self.driver.quit()
def init_driver(browser_name: str): def set_properties(browser_option): ua = Headers().generate() #fake user agent browser_option.add_argument('--headless') browser_option.add_argument('--disable-extensions') browser_option.add_argument('--incognito') browser_option.add_argument('--disable-gpu') browser_option.add_argument('--log-level=3') browser_option.add_argument(f'user-agent={ua}') browser_option.add_argument('--disable-notifications') browser_option.add_argument('--disable-popup-blocking') return browser_option try: browser_name = browser_name.strip().title() #automating and opening URL in headless browser if browser_name.lower() == "chrome": browser_option = ChromeOptions() browser_option = set_properties(browser_option) driver = webdriver.Chrome( ChromeDriverManager().install(), options=browser_option ) #chromedriver's path in first argument elif browser_name.lower() == "firefox": browser_option = FirefoxOptions() browser_option = set_properties(browser_option) driver = webdriver.Firefox( executable_path=GeckoDriverManager().install(), options=browser_option) else: driver = "Browser Not Supported!" return driver except Exception as ex: print(ex)
def setUp(self): options = ChromeOptions() options.add_argument("--window-size=1920,1080") self.driver = webdriver.Chrome(options=options) self.platforma_opon = platforma.PlatformaOpon(self.driver, platforma_login, platforma_password)
def get_webdriver_instance(self): """ 返回webdriver实例 """ if self.browser == 'chrome': if self.headless is True: chrome_option = ChromeOptions() chrome_option.add_argument('--headless') driver = webdriver.Chrome(executable_path=chrome_driver_path, chrome_options=chrome_option) else: driver = webdriver.Chrome(executable_path=chrome_driver_path) elif self.browser == 'firefox': if self.headless is True: firefox_options = FirefoxOptions() firefox_options.set_headless() driver = webdriver.Firefox(options=firefox_options, executable_path=firfox_driver_path) else: driver = webdriver.Firefox(executable_path=firfox_driver_path) elif self.browser == 'remote_firefox': driver = webdriver.Remote(command_executor='http://' + '1' + ':4444/wd/hub', desired_capabilities={ 'browserName': 'firefox', 'javascriptEnabled': True, }) elif self.browser == 'remote_chrome': driver = webdriver.Remote(command_executor='http://' + '2' + ':4444/wd/hub', desired_capabilities={ 'browserName': 'chrome', 'javascriptEnabled': True, }) elif self.browser == 'ie': ie_options = IEOptions() driver = webdriver.Ie(ie_options=ie_options, executable_path=ie_driver_path) elif self.browser == 'edge': driver = webdriver.Edge() elif self.browser == 'safari': driver = webdriver.Safari() else: driver = None if self.browser not in [ 'chrome', 'firefox', 'remote_firefox', 'remote_chrome', 'ie', 'edge', 'safari' ]: log.info('Driver "%s" is not defined' % self.browser) else: log.info('Driver is set as for browser "%s". Headless is %s' % (self.browser, self.headless)) driver.maximize_window() driver.implicitly_wait(5) driver.set_page_load_timeout(load_page_timeout) return driver
def browser(request): options = ChromeOptions() options.add_argument("--start-maximized") options.add_argument('--ignore-certificate-errors') # options.add_argument("--headless") d = DesiredCapabilities.CHROME d['loggingPrefs'] = {'browser': 'ALL'} browser = EventFiringWebDriver( webdriver.Chrome(options=options, desired_capabilities=d), SeleniumListener()) with allure.step("Start chrome browser for test."): def fin(): try: allure.attach(name=browser.session_id, body=str(browser.desired_capabilities), attachment_type=allure.attachment_type.JSON) allure.attach(name="chrome log", body=browser.get_log('browser'), attachment_type=allure.attachment_type.TEXT) except TypeError as e: logger.error(f'Oooops i got: {e}') finally: with allure.step("Closing browser."): browser.quit() request.addfinalizer(fin) return browser
def chrome_manager(self): opts = ChromeOptions() if self.on_travis: # github.com/travis-ci/travis-ci/issues/938 opts.add_argument("--no-sandbox") opts.add_argument("--load-extension=" + self.extension_path) opts.binary_location = self.browser_path opts.add_experimental_option( "prefs", {"profile.block_third_party_cookies": False}) # TODO not yet in Firefox (w/o hacks anyway): # https://github.com/mozilla/geckodriver/issues/284#issuecomment-456073771 opts.set_capability("loggingPrefs", {'browser': 'ALL'}) for i in range(5): try: driver = webdriver.Chrome(options=opts) except WebDriverException as e: if i == 0: print("") print("Chrome WebDriver initialization failed:") print(str(e) + "Retrying ...") else: break try: yield driver finally: driver.quit()
def __init__(self, username, login_user, login_pass, driver): self.username = username self.login_user = login_user self.login_pass = login_pass self.driver = driver # Use driver dependng on the chosen solution. # Driver has to be in PATH if self.driver == 'chromedriver': # Desde mediados de agosto los mamones de IG # detectan que estás conectado con Chromedriver o # con geckodriver. Incluimos la opción headless # para que no nos detecten. # Ver https://duo.com/decipher/driving-headless-chrome-with-python chrome_options = ChromeOptions() chrome_options.add_argument("--headless") self.browser = webdriver.Chrome(chrome_options=chrome_options) elif self.driver == 'geckodriver': # https://www.edureka.co/community/10026/headless-gecko-driver-using-selenium firefox_options = FirefoxOptions() firefox_options.add_argument("--headless") self.browser = webdriver.Firefox(firefox_options=firefox_options) self.url = "https://www.instagram.com/" + str(self.username)
def chromedriver_browser(executable_path, binary_location): options = ChromeOptions() options.binary_location = binary_location options.add_argument("--headless") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") return webdriver.Chrome(executable_path=executable_path, options=options)
printers.append(line.rstrip()) numEntries = inputUserInfo() print 'There was a total of ', numEntries, ' entered' printer = printers[0] #################################################### ##########SELENIUM BROWSER INTERACTION############## #################################################### # switched driver to selenium base driver for firefox # load default profile manually options = ChromeOptions() options.addArguments('user-data-dir=C:\Users\Carrio\AppData\Local\Google\Chrome\User Data\Default') # driver = webdriver.Firefox() # trying out chrome driver = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe', 0, options) # for printer in printers #for future use with all printers url = "http://" + printer + "/web/guest/en/websys/webArch/authForm.cgi" driver.get(url) # locate login and password forms loginform = driver.find_element_by_id('userid_work') passwordform = driver.driver.find_element_by_id('password_work') # type in user credentials loginform.send_keys(login[0])