Ejemplo n.º 1
0
def generate_driver(*, browser: str, config: Config):
    browser = browser.lower()

    if browser == 'firefox':
        driver = webdriver.Firefox()
        driver.maximize_window()

    elif browser == 'chrome':
        options = ChromeOptions()
        options.add_argument("--kiosk")
        options.add_argument("--disable-infobars")
        options.add_experimental_option("prefs",
                                        {"credentials_enable_service": False})
        driver = webdriver.Chrome(options=options)

    elif browser == 'headless':
        options = ChromeOptions()
        options.add_argument("headless")
        options.add_argument("no-sandbox")
        options.add_argument('window-size=1024,768')
        options.add_experimental_option("prefs",
                                        {"credentials_enable_service": False})
        driver = webdriver.Chrome(options=options)

    else:
        raise ValueError('Browser %s not recognized.' % browser)

    driver.implicitly_wait(5)
    driver.get(config.url)
    return driver
    def getBrowser(self):
        global _browser
        if _browser is None:
            # Use selenium
            logging.info("Creating Selenium webdriver using " + str(self.browser_type))

            # FIREFOX
            if self.browser_type == EBrowser.FIREFOX:
                binary = FirefoxBinary(self.firefox_binary)
                # see http://selenium-python.readthedocs.io/faq.html#how-to-auto-save-files-using-custom-firefox-profile
                if self.browser_user_profile:
                    profile = webdriver.FirefoxProfile(self.firefox_profile_path)
                else:
                    profile = webdriver.FirefoxProfile()
                _browser = webdriver.Firefox(firefox_binary=binary, firefox_profile=profile)
                self.sleep(1)
                _browser.set_window_position(0, 0)

            # PHANTOMJS
            elif self.browser_type == EBrowser.PHANTOMJS:
                dcap = dict(DesiredCapabilities.PHANTOMJS)
                useragent = ua.random
                dcap["phantomjs.page.settings.userAgent"] = useragent
                logging.info("Useragent='" + useragent + "'")
                _browser = webdriver.PhantomJS(executable_path=self.phantomjs_path, desired_capabilities=dcap)
                self.sleep(1)
                _browser.set_window_size(1920, 1080)
                self.sleep(1)

            # CHROME
            elif self.browser_type == EBrowser.CHROME:
                chrome_options = ChromeOptions()
                chrome_options.add_argument("--start-maximized")
                chrome_options.binary_location = self.chrome_binary
                _browser = webdriver.Chrome(chrome_options=chrome_options)
                self.sleep(3)

            # CHROME (headless)
            elif self.browser_type == EBrowser.CHROME_HEADLESS:
                chrome_options = ChromeOptions()
                chrome_options.add_argument("--headless")
                chrome_options.add_argument("--window-size={},{}".format(self.chrome_headless_screen_size[0],
                                                                         self.chrome_headless_screen_size[1]))
                chrome_options.binary_location = self.chrome_binary
                _browser = webdriver.Chrome(chrome_options=chrome_options)
                self.sleep(1)

            # OPERA
            elif self.browser_type == EBrowser.OPERA:
                opera_options = OperaOptions()
                opera_options.binary_location = r"C:\Program Files\Opera\launcher.exe"
                _browser = webdriver.Opera(opera_options=opera_options)
                self.sleep(5)

        return _browser
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    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)
Ejemplo n.º 6
0
    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(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()
Ejemplo n.º 7
0
    def __init__(self, uid, pswd, projectID, appWait, driver_type):
        self.uid = uid
        self.pswd = pswd
        self.projectID = projectID
        self.systemWait = appWait[0]
        self.longWait = appWait[1]
        self.midWait = appWait[2]
        self.shortWait = appWait[3]
        self.app_url = "https://accessibility.jp/libra/"
        self.index_url = "https://jis.infocreate.co.jp/"
        self.rep_index_url_base = "http://jis.infocreate.co.jp/diagnose/indexv2/report/projID/"
        self.rep_detail_url_base = "http://jis.infocreate.co.jp/diagnose/indexv2/report2/projID/"
        self.sv_mainpage_url_base = "http://jis.infocreate.co.jp/diagnose/indexv2/index/projID/"
        self.guideline_file_name = "guideline_datas.txt"
        self.rep_data = []

        # driverオプションの設定
        if driver_type == "chrome":
            options = ChromeOptions()
            options.executable_path = "/usr/bin/google-chrome"
            options.add_argument("--headless")
            options.add_argument("--dns-prefetch-disable")
            self.wd = webdriver.Chrome(options=options)
        else:
            pass

        self.wd.implicitly_wait(self.systemWait)
        self.wd.set_window_size(1280, 900)
        self.wd.get(self.app_url)
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
def new_driver(engine, save_file_dir):
    try:
        if engine == 'Chrome':
            options = ChromeOptions()
            options.add_experimental_option(
                "prefs", {
                    "download.default_directory": save_file_dir,
                    "download.prompt_for_download": False,
                    "download.directory_upgrade": True,
                    "safebrowsing.enabled": True
                })
            options.add_argument("--headless")
            driver = webdriver.Chrome(chrome_driver, chrome_options=options)
        elif engine == 'FireFox':
            profile = webdriver.FirefoxProfile()
            profile.set_preference('browser.download.folderList',
                                   2)  # custom location
            profile.set_preference('browser.download.manager.showWhenStarting',
                                   False)
            profile.set_preference('browser.download.dir', save_file_dir)
            profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
                                   'application/vnd.ms-excel')
            profile.set_preference('security.tls.version.min', 1)
            options = FirefoxOptions()
            driver = webdriver.Firefox(profile,
                                       options=options,
                                       executable_path=geckodriver_driver)
        else:
            driver = webdriver.PhantomJS(phantomjs_driver)
    except:
        driver = webdriver.PhantomJS(phantomjs_driver)
    return driver
Ejemplo n.º 10
0
    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()
Ejemplo n.º 11
0
 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 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()
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
    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 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!")
Ejemplo n.º 17
0
    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)
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
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})
Ejemplo n.º 21
0
def main():
    logger.info("Starting the browser")
    options = ChromeOptions()
    options.add_argument("--headless")
    driver = webdriver.Chrome(options=options)
    logger.info(
        "Browser started successfully. Navigating to the demo page to login")
    driver.get("https://www.saucedemo.com/")

    login(driver, 'standard_user', 'secret_sauce')

    # Get all inventory items
    inventory_items = driver.find_elements(By.CLASS_NAME, "inventory_item")

    # Add all items
    for item in inventory_items:
        title = item.find_element(By.CLASS_NAME, "inventory_item_name").text
        button = item.find_element(
            By.CSS_SELECTOR, "button[class='btn_primary btn_inventory']")
        add_to_cart(title, button)

    # Go to basket
    cart_button = driver.find_element(
        By.CSS_SELECTOR, "a[class='shopping_cart_link fa-layers fa-fw']")
    cart_button.click()

    # Get items in basket
    basket = driver.find_elements(By.CLASS_NAME, "cart_item")

    # Remove items
    for item in basket:
        title = item.find_element(By.CLASS_NAME, "inventory_item_name").text
        button = item.find_element(
            By.CSS_SELECTOR, "button[class='btn_secondary cart_button']")
        remove_from_cart(title, button)
Ejemplo n.º 22
0
    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)
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
    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_driver(browser_name):
        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()

            ua = Headers().generate()      #fake user agent
            #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)
Ejemplo n.º 26
0
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
Ejemplo n.º 27
0
def Translator(original):
    CHROMEDRIVER_PATH = './chromedriver'
    input1 = original
    chrome_op = ChromeOptions()
    chrome_op.add_argument('--headless')
    chrome_op.add_argument('--no-sandbox')
    # Provide text that you want to translate:=>
    print(input1)
    # launch browser with selenium:=>
    browser = webdriver.Chrome(
        CHROMEDRIVER_PATH
    )  #browser = webdriver.Chrome('path of chromedriver.exe file') if the chromedriver.exe is in different folder
    # copy google Translator link here:=>
    browser.get("https://translate.google.com")
    #view=home&op=translate&sl=en&tl="+lang_code)
    # Use Javascript command to give input text:=>
    command = "document.getElementById('source').value = '" + input1 + "'"
    # Excute above command:=>
    browser.execute_script(command)
    # just wait for some time for translating input text:=>
    time.sleep(6)
    # Given below x path contains the translated output that we are storing in output variable:=>
    output1 = browser.find_element_by_xpath(
        '/html/body/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/div[2]/div[3]/div[1]/div[2]/div/span[1]'
    ).text
    translated = output1
    # Display the output:=>
    print("Translated Paragraph:=> " + translated)
    time.sleep(6)
    browser.quit()
Ejemplo n.º 28
0
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
Ejemplo n.º 29
0
    def __init__(self, driver_name: str):

        driver_name = driver_name.casefold()

        if driver_name == "phantomjs":
            # --disk-cache=true allows to keep a cache
            self.driver = webdriver.PhantomJS(
                service_args=["--disk-cache=true"])
        elif driver_name in [
                "chrome",
                "chrome-headless",
                "chromium",
                "chromium-headless",
        ]:
            # TODO: find option to use custom profile with cache
            chrome_options = ChromeOptions()
            chrome_options.add_argument("--disable-gpu")  # most important line
            chrome_options.add_argument("--disable-extensions")
            if driver_name.endswith("-headless"):
                chrome_options.add_argument("--headless")
            self.driver = webdriver.Chrome(chrome_options=chrome_options)
        elif driver_name in ["firefox", "firefox-headless"]:
            # not working, disable gpu?
            options = FirefoxOptions()
            if driver_name.endswith("-headless"):
                options.add_argument("-headless")
            self.driver = webdriver.Firefox(firefox_options=options)
        else:
            raise Exception("Driver unknown")
Ejemplo n.º 30
0
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)