Esempio n. 1
0
def driver(browser):
    if browser == 'chrome':
        chrome_options = Chrome_options()
        chrome_options.add_argument("--disable-extensions")
        chrome_options.add_argument('--headless')
        capabilities = webdriver.DesiredCapabilities().CHROME
        driver = webdriver.Chrome(options=chrome_options,
                                  desired_capabilities=capabilities)
        logger.info("browser version: %s" % driver.capabilities['version'])

    elif browser == 'firefox':
        fp = webdriver.FirefoxProfile()
        fp.set_preference("dom.disable_beforeunload", True)
        firefox_options = Firefox_options()
        firefox_options.add_argument("--headless")
        capabilities = webdriver.DesiredCapabilities().FIREFOX.copy()
        capabilities['elementScrollBehavior'] = 1
        driver = webdriver.Firefox(options=firefox_options,
                                   firefox_profile=fp,
                                   capabilities=capabilities)

    elif browser == 'iphone':
        chrome_options = Chrome_options()
        chrome_options.add_argument("--disable-extensions")
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--hide-scrollbars")
        chrome_options.add_argument("--window-size=360,640")
        chrome_options.add_argument(
            "user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, "
            "like Gecko) Version/11.0 Mobile/15A372 Safari/604.1")
        capabilities = webdriver.DesiredCapabilities().CHROME
        driver = webdriver.Chrome(options=chrome_options,
                                  desired_capabilities=capabilities)
        logger.info("browser version: %s" % driver.capabilities['version'])

    elif browser == 'ipad':
        chrome_options = Chrome_options()
        chrome_options.add_argument("--disable-extensions")
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--hide-scrollbars")
        chrome_options.add_argument("--window-size=800,1024")
        chrome_options.add_argument(
            "user-agent=Mozilla/5.0 (iPad; CPU iPad OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1"
        )
        capabilities = webdriver.DesiredCapabilities().CHROME
        driver = webdriver.Chrome(options=chrome_options,
                                  desired_capabilities=capabilities)
        logger.info("browser version: %s" % driver.capabilities['version'])
    yield driver
    driver.delete_all_cookies()
    driver.quit()
    logger.info('close driver now')
Esempio n. 2
0
def make_browser():
    capabilities = webdriver.DesiredCapabilities().FIREFOX
    options = Options()
    options.add_argument("--headless")
    return webdriver.Firefox(firefox_options=options,
                             executable_path="/usr/bin/geckodriver",
                             capabilities=capabilities)
Esempio n. 3
0
class IsIdEnable():

    capabilities = webdriver.DesiredCapabilities().FIREFOX
    capabilities["marionette"] = False

    # Function to perform action, if the id is enabled otherwise, the action can't be performed
    def isEnable(self):
        driver = webdriver.Firefox()
        driver.get("https://www.google.com/")

        # Window Maximize
        driver.maximize_window()

        e1 = driver.find_element_by_id("gs_htif0")
        e1State = e1.is_enabled()
        print(" E1 is  -> " + str(e1State))

        driver.implicitly_wait(10)

        e2 = driver.find_element_by_id("gs_taif0")
        e2State = e2.is_enabled()
        print(" E2 is  -> " + str(e2State))

        # We can see in the DOM that e3 is not disable.
        # So, we can perform the action here by sending the data for google search.
        e3 = driver.find_element_by_id("lst-ib")
        e3State = e3.is_enabled()
        print(" E3 is  -> " + str(e3State))
        e3.send_keys("letskodeit")

        driver.close()
def getFireFoxProxyDriver():
    user_agent_list = xicidaili.getProxyUrls()
    myProxy = random.choice(user_agent_list)
    print(myProxy)
    proxy = Proxy({
        'proxyType': ProxyType.MANUAL,
        'httpProxy': myProxy,
        'ftpProxy': myProxy,
        'sslProxy': myProxy,
        'noProxy': ''  # set this value as desired
    })

    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    binary = FirefoxBinary(
        r'D:\Program Files\Mozilla Firefox\firefox.exe')  # 火狐浏览器地址
    # 属性
    fp = webdriver.FirefoxProfile()

    ua_random = ua.random
    print(ua_random)
    fp.set_preference('general.useragent.override', ua_random)
    fp.set_preference("permissions.default.stylesheet", 2)  # 限制css
    fp.set_preference("permissions.default.image", 2)  # 限制图片
    fp.set_preference("javascript.enabled", False)  # 禁止js
    # 浏览器 无界面
    fireFoxOptions = webdriver.FirefoxOptions()
    fireFoxOptions.headless = True
    driver = webdriver.Firefox(firefox_binary=binary,
                               firefox_profile=fp,
                               capabilities=caps,
                               firefox_options=fireFoxOptions,
                               proxy=proxy)

    return driver
Esempio n. 5
0
    def load_controllers(self, extensoes=[]):
        binary = FirefoxBinary(settings.MOZILLA_FIREFOX_TEST_PATH)
        capabilities = webdriver.DesiredCapabilities().FIREFOX
        """FirefoxOptions
        options = new
        FirefoxOptions();
        options.addPreference("--log", "error");
        """
        capabilities["marionette"] = True

        try:
            self.driver = webdriver.Firefox(
                firefox_binary=binary,
                executable_path=settings.SELENIUM_GECKODRIVER_MOZILLA,
                capabilities=capabilities)
            #self.driver.maximize_window()
            """ Especificando extensoes
            profile = webdriver.FirefoxProfile()
            for item in extensoes:
                profile.add_extension(extension=item)
            self.driver = webdriver.Firefox(firefox_profile=profile) """
            """ Carregar Mozilla Simples """

        except:
            print(
                "Navegador nao pode ser aberto. Pode ser necessario atualiza-lo antes."
            )
            exit(0)
    def inicializar_webdriver_chrome(self):

        webdriver_chrome = None

        opciones_chrome = webdriver.ChromeOptions()

        # ignora las certificaciones de seguridad, esto solamente se realiza
        # para la experiencia de usuario
        opciones_chrome.add_argument('--ignore-certificate-errors')
        opciones_chrome.add_argument("--headless")
        opciones_chrome.add_argument('--allow-running-insecure-content')
        opciones_chrome.add_argument("--enable-javascript")
        opciones_chrome.add_argument('window-size=1920x1080')
        opciones_chrome.add_argument('--no-sandbox')
        opciones_chrome.add_experimental_option('excludeSwitches', ['enable-logging'])

        chrome_capabilities = webdriver.DesiredCapabilities().CHROME.copy()
        chrome_capabilities['acceptSslCerts'] = True
        chrome_capabilities['acceptInsecureCerts'] = True

        try:
            webdriver_chrome = webdriver.Chrome(self.ruta_web_driver,
                                                chrome_options=opciones_chrome,
                                                desired_capabilities=chrome_capabilities,
                                                service_log_path=constantes_json.DEV_NULL)
        except FileNotFoundError as e:
            self.log.error('Sucedio un error al intentar configurar el webdriver: {}'.format(e))
        except Exception as e:
            self.log.error('Sucedio una excepcion al intentar configurar el webdriver {}'.format(e))

        return webdriver_chrome
Esempio n. 7
0
    def setUp(self):
        ff_binary = webdriver.firefox.firefox_binary.FirefoxBinary()
        ff_profile = webdriver.firefox.firefox_profile.FirefoxProfile()
        ff_profile.assume_untrusted_cert_issuer = True
        ff_profile.accept_untrusted_certs = True
        capabilities = webdriver.DesiredCapabilities().FIREFOX
        capabilities['acceptSslCerts'] = True
        self.driver = webdriver.Firefox(firefox_binary=ff_binary,
                                        firefox_profile=ff_profile,
                                        capabilities=capabilities,
                                        timeout=60)
        self.driver.implicitly_wait(30)
        self.wait = WebDriverWait(self.driver, 30)
        self.base_url = "https://127.0.0.1:8000/"
        self.verificationErrors = []
        self.accept_next_alert = True

        permissions_db_path = os.path.join(ff_profile.profile_dir,
                                           "permissions.sqlite")

        with contextlib.closing(sqlite3.connect(permissions_db_path)) as db:
            cur = db.cursor()
            cur.execute(("INSERT INTO moz_perms VALUES (1, '{base_url}', "
                         "'popup', 1, 0, 0, 1474977124357)").format(
                             base_url=self.base_url))
            db.commit()
Esempio n. 8
0
def browser(browser='firefox'):
    """
    打开浏览器函数,"firefox"、"chrome"、"ie"、"phantomjs"
    """
    try:
        if browser == "firefox":
            profile = webdriver.FirefoxProfile(
                r'C:\Users\ditto.he\AppData\Roaming\Mozilla\Firefox\Profiles\r8tbe0ai.default'
            )
            profile.accept_untrusted_certs = True
            driver = webdriver.Firefox(firefox_profile=profile)
            return driver
        elif browser == "chrome":
            options = webdriver.ChromeOptions()
            options.add_argument('--ignore-certificate-errors')
            driver = webdriver.Chrome(chrome_options=options)
            return driver
        elif browser == "ie":
            capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
            capabilities['acceptSslCerts'] = True
            driver = webdriver.Ie(capabilities=capabilities)
            return driver
        elif browser == "phantomjs":
            driver = webdriver.PhantomJS()
            return driver
        else:
            print(
                "Not found this browser,You can enter 'firefox', 'chrome', 'ie' or 'phantomjs'"
            )
    except Exception as msg:
        print "browser error is : %s" % msg
    def _get_existing_driver_session(session_id, executor_url):
        from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver

        capabilities = webdriver.DesiredCapabilities().FIREFOX.copy()
        capabilities["unexpectedAlertBehaviour"] = "accept"

        # Save the original function, so we can revert our patch
        org_command_execute = RemoteWebDriver.execute

        def new_command_execute(context, command, params=None):
            if command == "newSession":
                # Mock the response
                return {
                    'success': 0,
                    'value': None,
                    'sessionId': session_id,
                    'capabilities': capabilities
                }
            else:
                return org_command_execute(context, command, params)

        # Patch the function before creating the driver object
        RemoteWebDriver.execute = new_command_execute

        new_driver = webdriver.Remote(command_executor=executor_url,
                                      desired_capabilities=capabilities)
        # browser_profile=firefox_profile,
        new_driver.session_id = session_id
        new_driver._is_remote = True

        # Replace the patched function with original function
        RemoteWebDriver.execute = org_command_execute

        return new_driver
Esempio n. 10
0
def test():
    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    binary = FirefoxBinary(r'D:\Program Files\Mozilla Firefox\firefox.exe')
    # 把上述地址改成你电脑中Firefox程序的地址
    driver = webdriver.Firefox(firefox_binary=binary, capabilities=caps)
    driver.get("http://www.santostang.com/2018/07/04/hello-world/")
    def inicializar_webdriver_firefox(self):
        # ruta para deshabilitar log inecesario del geckodriver
        webdriver_firefox = None
        opciones_firefox = webdriver.FirefoxOptions()
        perfil_firefox = webdriver.FirefoxProfile()

        firefox_capabilities = webdriver.DesiredCapabilities().FIREFOX.copy()
        firefox_capabilities.update(
            {'acceptInsecureCerts': True, 'acceptSslCerts': True})
        firefox_capabilities['acceptSslCerts'] = True

        # ignora las certificaciones de seguridad, esto solamente se realiza
        # para la experiencia de usuario
        opciones_firefox.add_argument('--ignore-certificate-errors')
        opciones_firefox.accept_insecure_certs = True
        perfil_firefox.accept_untrusted_certs = True
        perfil_firefox.assume_untrusted_cert_issuer = False

        opciones_firefox.headless = False
        try:
            webdriver_firefox = webdriver.Firefox(executable_path=self.ruta_web_driver,
                                                  firefox_options=opciones_firefox,
                                                  firefox_profile=perfil_firefox,
                                                  capabilities=firefox_capabilities,
                                                  #log_path=constantes_json.DEV_NULL
                                                  )
        except FileNotFoundError as e:
            self.log.error('Sucedio un error al intentar configurar el webdriver: {}'.format(e))
        except Exception as e:
            self.log.error('Sucedio una excepcion al intentar configurar el webdriver {}'.format(e))

        return webdriver_firefox
def remote_driver(t_browser, page_load_strategy=None):
    """ Remote driver """
    logging.debug('remote driver config start')
    remote_mapping = {
        'chrome': {
            'command_executor':
            'http://selenium__standalone-chrome:4444/wd/hub',
            'options': webdriver.ChromeOptions()
        },
        'firefox': {
            'command_executor':
            'http://selenium__standalone-firefox:4444/wd/hub',
            'options': webdriver.FirefoxOptions()
        }
    }
    if page_load_strategy:
        desired_capabilities = webdriver.DesiredCapabilities().CHROME
        desired_capabilities["pageLoadStrategy"] = "eager"

    driver = webdriver.Remote(
        command_executor=remote_mapping[t_browser]['command_executor'],
        options=remote_mapping[t_browser]['options'])
    driver.set_page_load_timeout(20)
    browser = Browser(
        Config(
            driver=driver,
            timeout=10,
            window_width=1500,
            window_height=1200,
        ))
    logging.debug('remote driver config finish')
    return browser
Esempio n. 13
0
    def __init__(self,is_headless):
        chrome_options = Options()
        if is_headless:
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--disable-gpu')
            chrome_options.add_argument('--no-sandbox')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('lang=zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7')
        chrome_options.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
        chrome_options.add_argument("disable-blink-features=AutomationControlled")
        chrome_options.add_argument('log-level=1')
        capabilities = webdriver.DesiredCapabilities().CHROME
        capabilities['acceptSslCerts'] = True
        capabilities['goog:loggingPrefs'] = {'browser': 'ALL','performance': 'ALL'}
        if ifproxy == 'true':
            chrome_options.add_argument('proxy-server=' + proxy)

        if system == 'Linux':
            try:
                self.dr = webdriver.Chrome(options=chrome_options,desired_capabilities=capabilities)
            except:
                self.dr = webdriver.Chrome(executable_path=os.path.abspath(os.path.join("app", "bin","chromedriver")),options=chrome_options,desired_capabilities=capabilities)
        elif system == 'Windows':
            self.dr = webdriver.Chrome(executable_path=os.path.abspath(os.path.join("app", "bin","chromedriver.exe")),options=chrome_options,desired_capabilities=capabilities)
        self.dr.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
            'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
        })
class RadioButtonFindElements():

    capabilities = webdriver.DesiredCapabilities().FIREFOX
    capabilities["marionette"] = False

    def radioFindElementsList(self):
        driver = webdriver.Firefox()
        url = "https://letskodeit.teachable.com/p/practice"
        driver.get(url)
        driver.maximize_window()
        driver.implicitly_wait(20)

        radioButtonList = driver.find_elements(
            By.XPATH,
            "//input[contains(@type,'radio') and contains(@name,'cars')]")

        listSize = len(radioButtonList)
        print("Size of the Radio Button List is ...  " + str(listSize))

        for radioButton in radioButtonList:
            isSelected = radioButton.is_selected()

            if not isSelected:
                radioButton.click()
                time.sleep(2)

        driver.close()
Esempio n. 15
0
class DropDownSelect():
    capabilities = webdriver.DesiredCapabilities().FIREFOX
    capabilities["marionette"] = False

    def dropDown(self):
        driver = webdriver.Firefox()
        url = "https://letskodeit.teachable.com/p/practice"
        driver.get(url)
        driver.maximize_window()
        driver.implicitly_wait(20)

        element = driver.find_element_by_id("carselect")
        sel = Select(element)

        print("Select BMW by Value")
        sel.select_by_value("bmw")
        time.sleep(2)

        print("Select BENZ by index")
        sel.select_by_index(1)
        time.sleep(2)

        print("Select HONDA by Visible Text")
        sel.select_by_visible_text("Honda")
        time.sleep(2)

        print("Select BMW by index")
        sel.select_by_index(0)
        time.sleep(2)

        driver.close()
Esempio n. 16
0
def getProxyUrls():
    url = "https://www.xicidaili.com/wt/"

    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    binary = FirefoxBinary(
        r'D:\Program Files\Mozilla Firefox\firefox.exe')  # 火狐浏览器地址
    # 属性
    fp = webdriver.FirefoxProfile()
    fp.set_preference("permissions.default.stylesheet", 2)  # 限制css
    fp.set_preference("permissions.default.image", 2)  # 限制图片
    fp.set_preference("javascript.enabled", False)  # 禁止js
    # 浏览器 无界面
    fireFoxOptions = webdriver.FirefoxOptions()
    fireFoxOptions.headless = True
    driver = webdriver.Firefox(firefox_binary=binary,
                               firefox_profile=fp,
                               capabilities=caps,
                               firefox_options=fireFoxOptions)
    driver.get(url)  # 打开网页
    time.sleep(3)  # 等一下 等页面加载好
    tds = driver.find_elements_by_xpath(
        '/html[1]/body[1]/div[1]/div[2]/table[1]/tbody[1]/tr[*]/td[2]')
    proxys = []
    for td in tds:
        proxys.append(td.text)

    driver.close()
    return proxys


# urls = getProxyUrls()
# print(urls)
Esempio n. 17
0
def git_automation(reponame, username, password, readme, commit):
    """
    Git site automate with selenium
    """

    #--| Setup
    options = Options()
    options.add_argument("--headless")
    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    browser = webdriver.Firefox(
        firefox_options=options,
        capabilities=caps,
        executable_path=r"./geckodriver")  #without opening the browser
    # browser = webdriver.Firefox(executable_path='./geckodriver')#penig the browser
    # browser.set_window_size(900, 900)
    browser.get('https://github.com/login')

    usrname = browser.find_element_by_xpath('//*[@id="login_field"]')
    usrname.send_keys(username)
    passw = browser.find_element_by_xpath('//*[@id="password"]')
    passw.send_keys(password)
    sign = browser.find_element_by_xpath(
        '//*[@id="login"]/form/div[4]/input[9]')
    sign.click()

    try:
        sign_error = browser.find_element_by_xpath(
            '//*[@id="js-flash-container"]/div/div')
        print(sign_error.text)
        add_repo(browser, reponame, readme, commit)
    except NoSuchElementException as e:
        # print(e)
        add_repo(browser, reponame, readme, commit)
class RadioAndCheckBox():

    capabilities = webdriver.DesiredCapabilities().FIREFOX
    capabilities["marionette"] = False

    def isSelected(self):
        driver = webdriver.Firefox()
        url = "https://letskodeit.teachable.com/p/practice"
        driver.get(url)
        driver.maximize_window()
        driver.implicitly_wait(20)

        bmw_rd = driver.find_element_by_id("bmwradio")
        bmw_rd.click()
        time.sleep(2)

        benz_rd = driver.find_element_by_id("benzradio")
        benz_rd.click()
        time.sleep(2)

        bmw_chk = driver.find_element_by_id("bmwcheck")
        bmw_chk.click()
        time.sleep(2)

        bennz_chk = driver.find_element_by_id("benzcheck")
        bennz_chk.click()
        # time.sleep(2)

        print("BMW Radio Button is Selected ?  " + str(bmw_rd.is_selected()))
        print("BENZ Radio Button is Selected ?  " + str(benz_rd.is_selected()))
        print("BMW Radio Button is Selected ?  " + str(bmw_chk.is_selected()))
        print("BENZ Radio Button is Selected ?  " +
              str(bennz_chk.is_selected()))

        driver.close()
Esempio n. 19
0
def getProComment():
    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = False
    binary = FirefoxBinary(r'fixefox')
    fp = webdriver.FirefoxProfile()
    fp.set_preference("permissions.default.stylesheet",2)
    driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=fp, capabilities=caps)
    driver.get("http://www.santostang.com/2017/03/02/hello-world/")
Esempio n. 20
0
def sstart():
	new_prof()
	capabilities = webdriver.DesiredCapabilities().FIREFOX
	capabilities["marionette"] = True
	profile = webdriver.FirefoxProfile(path_profile)
	binary = FirefoxBinary(Binarry)
	driver = webdriver.Firefox(firefox_binary=binary , capabilities=capabilities , firefox_profile=profile , executable_path=gecko_path)
	return driver
 def createWebDriver(self):
     capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
     #capabilities['acceptSslCerts'] = True
     driver = webdriver.Ie(
         executable_path="C:\\MyWorkspace\\IEDriver\\IEDriverServer.exe",
         capabilities=capabilities)
     driver.maximize_window()
     return driver
Esempio n. 22
0
def start_firefox(html):
    capabilities = webdriver.DesiredCapabilities().FIREFOX
    capabilities["marionette"] = False
    binary = FirefoxBinary(r'/usr/bin/firefox')
    bow = webdriver.Firefox(firefox_binary=binary, capabilities=capabilities)
    bow.get("file:///home/pi/python-controler/view/" + html + ".html")
    bow.maximize_window()
    return bow
Esempio n. 23
0
 def setUp(self):
     capabilities = webdriver.DesiredCapabilities().FIREFOX
     capabilities["marionette"] = False
     self.driver = webdriver.Firefox()
     self.driver.implicitly_wait(30)
     self.base_url = "https://www.baidu.com"
     self.verificationErrors = []
     self.accept_next_alert = True
    def inicializar_webdriver_chrome(self):

        archivo_config_ini = FormatUtils.lector_archivo_ini()
        modo_headless = archivo_config_ini.getboolean('Driver', 'headless')
        mandar_log_a_dev_null = archivo_config_ini.getboolean(
            'Driver', 'log_path_dev_null')

        opciones_chrome = webdriver.ChromeOptions()

        # ignora las certificaciones de seguridad, esto solamente se realiza para la experiencia de usuario
        opciones_chrome.add_argument('--ignore-certificate-errors')
        opciones_chrome.add_argument('--allow-running-insecure-content')
        opciones_chrome.add_argument("--enable-javascript")
        opciones_chrome.add_argument('window-size=1920x1080')
        opciones_chrome.add_argument('--no-sandbox')
        opciones_chrome.add_argument('--disable-dev-shm-usage')

        # establece el modo headless, esto dependiendo de la opcion que se tenga en el archivo config.ini
        if modo_headless:
            opciones_chrome.add_argument("--headless")

        opciones_chrome.add_experimental_option('excludeSwitches',
                                                ['enable-logging'])

        opciones_chrome.add_experimental_option('prefs', {
            'download.default_directory':
            config_constantes.PATH_CARPETA_DESCARGA
        })

        chrome_capabilities = webdriver.DesiredCapabilities().CHROME.copy()
        chrome_capabilities['acceptSslCerts'] = True
        chrome_capabilities['acceptInsecureCerts'] = True

        # establece el directorio al cual se redireccionara el log generado por el chromedriver
        if mandar_log_a_dev_null:
            param_service_log_path = config_constantes.DEV_NULL
        else:
            param_service_log_path = None

        try:
            webdriver_chrome = webdriver.Chrome(
                self.ruta_web_driver,
                chrome_options=opciones_chrome,
                desired_capabilities=chrome_capabilities,
                service_log_path=param_service_log_path)

        except FileNotFoundError as e:
            print('Sucedio un error al intentar configurar el webdriver: {}'.
                  format(e))
            sys.exit()

        except Exception as e:
            print(
                'Sucedio una excepcion al intentar configurar el webdriver {}'.
                format(e))
            sys.exit()

        return webdriver_chrome
Esempio n. 25
0
def push_to_listserv(emails_file):

    profile = webdriver.FirefoxProfile()
    profile.accept_untrusted_certs = True
    profile.assume_untrusted_cert_issuer = True
    capabilities = webdriver.DesiredCapabilities().FIREFOX.copy()
    capabilities['acceptInsecureCerts'] = True
    browser = webdriver.Firefox(firefox_profile=profile,
                                capabilities=capabilities)
    try:
        _create_unverified_https_context = ssl._create_unverified_context
    except AttributeError:
        # Legacy Python that doesn't verify HTTPS certificates by default
        pass
    else:
        # Handle target environment that doesn't support HTTPS verification
        ssl._create_default_https_context = _create_unverified_https_context

    # Open login page and wait till it loads
    browser.get(settings.LISTSERV_FORM_ADDRESS)
    wait.WebDriverWait(browser, 10).until(
        expected_conditions.element_to_be_clickable(
            (By.XPATH, "//form/p/input[1]")))

    # Submit login info
    email_field = browser.find_element_by_id("Email Address")
    email_field.clear()
    email_field.send_keys(settings.LISTSERV_USERNAME)
    password_field = browser.find_element_by_id("Password")
    password_field.clear()
    password_field.send_keys(settings.LISTSERV_PASSWORD)
    email_field.submit()

    # Wait for login request to complete
    wait.WebDriverWait(browser, 10).until(
        expected_conditions.element_to_be_clickable((By.ID, "Input File")))

    # Open the email upload page and submit the form
    replace_all_button = browser.find_element_by_id("radiob")
    replace_all_button.click()
    file_upload = browser.find_element_by_id("Input File")

    file_upload.send_keys(emails_file)

    print("Waiting for file upload...")
    time.sleep(LOAD_WAIT_SECS)

    file_upload.submit()

    # TODO: parse response and notify someone
    print("Waiting for listserv to process...")
    time.sleep(LOAD_WAIT_SECS)

    print('pause')
    change_message = browser.find_element_by_class_name('message').text

    return change_message
Esempio n. 26
0
 def __loadDriver(self):
     capabilities = webdriver.DesiredCapabilities().CHROME.copy()
     capabilities["acceptInsecureCerts"] = True
     self.driver = webdriver.Chrome(
         options=self.__chrome_options(),
         service_args=["--verbose", "--log-path=./chromedriver.log"],
         desired_capabilities=capabilities,
         executable_path="./chromedriver",
     )  # noqa
Esempio n. 27
0
def firefox_driver():
    # Doesn't work with geckodriver! :(
    capabilities = webdriver.DesiredCapabilities().FIREFOX
    capabilities['acceptSslCerts'] = True

    profile = webdriver.FirefoxProfile()
    profile.accept_untrusted_certs = True

    return webdriver.Firefox(firefox_profile=profile, capabilities=capabilities)
Esempio n. 28
0
def create_firefox_driver():
    capabilities = webdriver.DesiredCapabilities().FIREFOX.copy()
    capabilities['acceptSslCerts'] = True
    profile = FirefoxProfile()
    profile.set_preference('media.navigator.streams.fake', True)
    profile.set_preference('media.navigator.permission.disabled', True)

    return webdriver.Firefox(firefox_profile=profile,
                             capabilities=capabilities)
Esempio n. 29
0
def webDriver():
    # marionette setting is fixed in selenium 3.0 and above by default
    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = False
    global driver
    driver = webdriver.Firefox(capabilities=caps)
    driver.implicitly_wait(30)
    driver.maximize_window()
    return driver
Esempio n. 30
0
def del_repo(username, password, repoName):
    #--| Setup
    options = Options()
    options.add_argument("--headless")
    caps = webdriver.DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    browser = webdriver.Firefox(
        firefox_options=options,
        capabilities=caps,
        executable_path=r"./geckodriver")  #without opening the browser
    # browser = webdriver.Firefox(executable_path='./geckodriver')
    # browser.set_window_size(900, 900)
    browser.get('https://github.com/login')

    usrname = browser.find_element_by_xpath('//*[@id="login_field"]')
    usrname.send_keys(username)
    passw = browser.find_element_by_xpath('//*[@id="password"]')
    passw.send_keys(password)
    sign = browser.find_element_by_xpath(
        '//*[@id="login"]/form/div[4]/input[9]')
    sign.click()

    try:
        sign_error = browser.find_element_by_xpath(
            '//*[@id="js-flash-container"]/div/div')
        print(sign_error.text)
    except NoSuchElementException as e:
        time.sleep(2)
        home_page = browser.current_url
        #go to the project repository page
        browser.get(f'{home_page}{username}/{repoName}')
        #go to repository settings
        settings = browser.find_element_by_xpath(
            '//*[@id="js-repo-pjax-container"]/div[1]/nav/a[5]')
        settings.click()
        #delete repository
        time.sleep(5)
        delete_btn = browser.find_element_by_xpath(
            '/html/body/div[4]/div/main/div[2]/div/div/div[2]/div/div[8]/ul/li[4]/details/summary'
        )
        # delete_btn = browser.find_elements_by_class_name('btn-danger')
        delete_btn.click()
        time.sleep(2)
        #confirm delection of the repository
        confirm_input = browser.find_element_by_xpath(
            '//*[@id="options_bucket"]/div[8]/ul/li[4]/details/details-dialog/div[3]/form/p/input'
        )
        confirm_input.send_keys(f'{username}/{repoName}')
        confirm_btn = browser.find_element_by_xpath(
            '//*[@id="options_bucket"]/div[8]/ul/li[4]/details/details-dialog/div[3]/form/button'
        )
        confirm_btn.click()
        click.secho((f'Repository {repoName} delected succesfully'),
                    fg=const.SUCCES_CLR)


# gw.git_automation('test', 'assignon', 'Serges@007', True, 'First commit')