def __init__(self, queue): super(DriverThread, self).__init__() self.queue = queue proxyServer = 'localhost:8080' proxy = Proxy() proxy.setHttpProxy(proxyServer) proxy.setSslProxy(proxyServer) capabilities = DesiredCapabilities() capabilities.setCapability(CapabilityType.PROXY, proxy) self.driver = FirefoxDriver(capabilities)
def login(): ''' Fonction permettant se récupérer le cookie de session après une connexion via selenium ''' firefoxOptions = FirefoxOptions() #firefoxOptions.addArguments("--window-size=1920,1080") #firefoxOptions.addArguments("--disable-gpu") #firefoxOptions.addArguments("--disable-extensions") #firefoxOptions.addArguments("--proxy-server='direct://'") #firefoxOptions.addArguments("--proxy-bypass-list=*") #firefoxOptions.addArguments("--start-maximized") firefoxOptions.addArguments("--headless") webDriver = FirefoxDriver(firefoxOptions) webDriver.get(URL_LOGIN) timeOut = 3 waiter = WebDriverWait(webDriver, timeOut) waiter.until(ExpectedConditions.visibilityOfElement(By.id("login-form"))) webDriver.findElement(By.name("email")).sendKeys("*****@*****.**") webDriver.findElement(By.name("pass")).sendKeys("123") webDriver.findElement(By.name("login-button")).click() waiter.until(ExpectedConditions.visibilityOfElement(By.id("welcome-page"))) GlobalVariables.setGlobalCustomVar( COOKIE, str(webDriver.manage().getCookieNamed(COOKIE_NAME).getValue()))
class DriverThread(Thread): def __init__(self, queue): super(DriverThread, self).__init__() self.queue = queue proxyServer = 'localhost:8080' proxy = Proxy() proxy.setHttpProxy(proxyServer) proxy.setSslProxy(proxyServer) capabilities = DesiredCapabilities() capabilities.setCapability(CapabilityType.PROXY, proxy) self.driver = FirefoxDriver(capabilities) def run(self): firstRun = True while True: url = self.queue.get() if not firstRun: self._acceptAlerts() elif firstRun: firstRun = False if not url: break sys.stdout.write('Fetching %s... ' % url) self.driver.get(url) print 'done.' self.queue.task_done() self.queue.task_done() self.driver.close() def _acceptAlerts(self): print '\n------ BEGIN ALERTS ------\n' while True: try: alert = self.driver.switchTo().alert() print 'javascript:alert(%s);' % repr(alert.getText()) alert.dismiss() except NoAlertPresentException: print '\n------ END ALERTS ------\n' self.driver.switchTo().defaultContent() return
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class Book { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.gecko.driver", "E:\\Automation\\sagar\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("http://nepalinn.com/search/result"); Thread.sleep(5000); driver.findElement(By.xpath("//*[@name = 'submit_search']")).click(); Thread.sleep(4000); WebElement text1 = driver.findElement(By.xpath(".//*[text()='Hotel New Solitary Lodge']")); String text2 = driver.findElement(By.xpath(".//*[text()='Hotel New Solitary Lodge']")).getText(); System.out.println(text2); String Hotel_name = "HOTEL NEW SOLITARY LODGE"; if (text2.equals(Hotel_name)) { driver.findElement(By.xpath("//*[@href= 'http://nepalinn.com/hotel_new_solitary_lodge']//button[text()='Book']")).click();
def open_browser(self, url, browser): #self._logger.error('open_browser(' + url + ', ' + browser +')') self.__firefoxDriver=FirefoxDriver() self.__firefoxDriver.get(url)
class InewSelenium2Library: ROBOT_LIBRARY_SCOPE = 'TEST CASE' ROBOT_LIBRARY_VERSION = '0.2' def __init__(self): self._logger = logging.getLogger('scope.name') file_log_handler = logging.FileHandler('logfile.log') self._logger.addHandler(file_log_handler) stderr_log_handler = logging.StreamHandler() self._logger.addHandler(stderr_log_handler) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_log_handler.setFormatter(formatter) stderr_log_handler.setFormatter(formatter) self.__firefoxDriver=None self._speed = 0.4 def open_browser(self, url, browser): #self._logger.error('open_browser(' + url + ', ' + browser +')') self.__firefoxDriver=FirefoxDriver() self.__firefoxDriver.get(url) def maximize_browser_window(self): #self._logger.error('maximize_browser_window()') #self.__firefoxDriver.maximize_window() dosomething='here' def close_browser(self): #self.__firefoxDriver.close(url) #TODO: Find out why the Browser instance is not killed by close() #self.__firefoxDriver.close() self.__firefoxDriver.quit() self.__firefoxDriver = None def set_selenium_speed(self, seconds): #self._logger.error('set_selenium_speed()') self._speed=seconds def get_selenium_speed(self): return self._speed def save_screenshot(self, filepath): tempfile = self.__firefoxDriver.getScreenshotAs(OutputType.FILE) FileUtils.copyFile(tempfile, File(filepath)) def input_text(self, locator, text): #self._logger.error('input_text(' + locator + ', ' + text+')') element = self._find_element(locator) element.sendKeys(text); def go_to(self, url): #self._logger.error('go_to(' + url + ')') self.__firefoxDriver.get(url) def click_element(self, locator): #self._logger.error('click_element(' + locator + ')') element = self._find_element(locator) element.click(); def page_contains_element(self, locator): return self._is_element_present(locator) def wait_until_page_contains_element(self, locator, timeout=None, error=None): if not error: error = "Element '%s' did not appear in <TIMEOUT>" % locator self._wait_until(timeout, error, self._is_element_present, locator) def select_frame(self, locator): #self._logger.error('select_frame(' + locator + ')') element = self._find_element(locator) #self.__firefoxDriver.switch_to_frame(element) self.__firefoxDriver.switchTo().frame(element) def unselect_frame(self): #self.__firefoxDriver.switch_to_default_content() self.__firefoxDriver.switchTo().defaultContent() def get_table_cell(self, table_locator, row, column, loglevel='INFO'): #self._logger.error('get_table_cell(' + table_locator + ', ' + row + ', ' + column + ')') row = int(row) row_index = row - 1 column = int(column) column_index = column - 1 tableElement = self._find_element(table_locator) if tableElement is not None: rows = tableElement.findElementsByXPath("./thead/tr") if row_index >= len(rows): rows.addAll(tableElement.findElementsByXPath("./tbody/tr")) if row_index >= len(rows): rows.addAll(tableElement.findElementsByXPath("./tfoot/tr")) if row_index < len(rows): columns = rows[row_index].findElementsByTagName('th') if column_index >= len(columns): columns.addAll(rows[row_index].findElementsByTagName('td')) if column_index < len(columns): return columns[column_index].text raise AssertionError("Cell in table %s in row #%s and column #%s could not be found." % (table_locator, str(row), str(column))) ############### private ################### def _find_element(self, locator): splitLocator=locator.split("=") #id/name/link=value strategy='' value='' if locator.startswith( '//' ): strategy='xpath' value = splitLocator[0] elif len(splitLocator)==2: strategy=splitLocator[0] value = splitLocator[1] else: #default strategy strategy='id' value = splitLocator[0] element = None if strategy == 'id': #element = self.__firefoxDriver.findElement(By.id(value)) element = self.__firefoxDriver.findElementById(value) elif strategy == 'name': #element = self.__firefoxDriver.findElement(By.name(value)) element = self.__firefoxDriver.findElementByName(value) elif strategy == 'link': element = self.__firefoxDriver.findElementByLinkText(value) elif strategy == 'xpath': element = self.__firefoxDriver.findElementByXPath(locator) else: raise AssertionError('Unknown locator strategy: ' + locator) return element def _wait_until(self, timeout, error, function, *args): error = error.replace('<TIMEOUT>', self._format_timeout(timeout)) def wait_func(): return None if function(*args) else error self._wait_until_no_error(timeout, wait_func) def _wait_until_no_error(self, timeout, wait_func, *args): timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs maxtime = time.time() + timeout while True: timeout_error = wait_func(*args) if not timeout_error: return if time.time() > maxtime: raise AssertionError(timeout_error) time.sleep(0.2) def _format_timeout(self, timeout): timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs return robot.utils.secs_to_timestr(timeout) def _is_element_present(self, locator): elementFound = 'true' try: element = self._find_element(locator) except: elementFound = 'false' return elementFound
def doLogin(helper): firefoxOptions = FirefoxOptions() firefoxOptions.addArguments("--window-size=1920,1080"); firefoxOptions.addArguments("--disable-gpu"); firefoxOptions.addArguments("--disable-extensions"); firefoxOptions.addArguments("--proxy-server='direct://'"); firefoxOptions.addArguments("--proxy-bypass-list=*"); firefoxOptions.addArguments("--start-maximized"); firefoxOptions.addArguments("--headless"); webDriver = FirefoxDriver(firefoxOptions); # generate state and nonce state = generateRandomAlphanumericString(20); nonce = generateRandomAlphanumericString(20); print "state:"+state; print "nonce:"+nonce; #------------getting login page from keycloak------------ loginUrl = KEYCLOAK_BASE_URL+"/realms/"+KEYCLOAK_REALM+"/protocol/openid-connect/auth?client_id=app-angular2&redirect_uri="+ENCODED_APP_ANGULAR_URL+"%2F&state="+state+"&nonce="+nonce+"&response_mode=fragment&response_type=code&scope=openid"; print("loginUrl:"+loginUrl); webDriver.get(loginUrl); # we wait until the username element is visible timeoutInSeconds = 10; wait = WebDriverWait(webDriver, timeoutInSeconds); wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("username"))); loginEle = webDriver.findElement(By.name("username")); formEle = webDriver.findElement(By.id("kc-form-login")); # gathering all the information to make the next http request formActionUrl = formEle.getAttribute("action"); formBody = "username="******"&password="******"&credentialId=" authSessionIdLegacyCookieValue = webDriver.manage().getCookieNamed(AUTH_SESSION_ID_LEGACY_COOKIE_NAME).getValue(); print "authSessionIdLegacyCookieValue: " + authSessionIdLegacyCookieValue; kcRestartCookieValue = webDriver.manage().getCookieNamed(KC_RESTART_COOKIE_NAME).getValue(); print "kcRestartCookieValue: " + kcRestartCookieValue; authSessionIdLegacyCookie = HttpCookie(AUTH_SESSION_ID_LEGACY_COOKIE_NAME, authSessionIdLegacyCookieValue); kcRestartCookie = HttpCookie(KC_RESTART_COOKIE_NAME, kcRestartCookieValue); cookies = [authSessionIdLegacyCookie, kcRestartCookie]; #----------------------------------------------------- #------------submitting login credentials to keycloak------------ returnedMsg = callPost(formActionUrl, formBody, {}, cookies, "application/x-www-form-urlencoded", helper); keyCloakIdentityLegacyCookieValue = returnedMsg.getResponseHeader().getHeader(KEYCLOAK_IDENTITY_LEGACY_COOKIE_NAME) keyCloakSessionLegacyCookieValue = returnedMsg.getResponseHeader().getHeader(KEYCLOAK_SESSION_LEGACY_COOKIE_NAME); # we will get a redirect response whose url in the 'location' header we will need to call manually below to get the token # we cannot use selenium at this stage as it will do auto redirect and we will miss the information returned by the redirect response location = returnedMsg.getResponseHeader().getHeader("Location"); print "location: " + location; codeQueryParamValue = getUrlQueryParamValue(location, "code"); print("code:" + codeQueryParamValue); tokenUrl = KEYCLOAK_BASE_URL+"/realms/"+KEYCLOAK_REALM+"/protocol/openid-connect/token" formBody = "code="+codeQueryParamValue+"&grant_type=authorization_code&client_id=app-angular2&redirect_uri="+ENCODED_APP_ANGULAR_URL+"%2F"; keyCloakIdentityLegacyCookie = HttpCookie(KEYCLOAK_IDENTITY_LEGACY_COOKIE_NAME, keyCloakIdentityLegacyCookieValue); keyCloakSessionLegacyCookie = HttpCookie(KEYCLOAK_SESSION_LEGACY_COOKIE_NAME, keyCloakSessionLegacyCookieValue); cookies = [authSessionIdLegacyCookie, keyCloakIdentityLegacyCookie, keyCloakSessionLegacyCookie]; #----------------------------------------------------- #-----------calling the url in the 'location' header to get the access token----------- returnedMsg = callPost(tokenUrl, formBody, {}, cookies, "application/x-www-form-urlencoded", helper); authenticatedJsonResponseObject = json.loads(str(returnedMsg.getResponseBody())); accessToken = authenticatedJsonResponseObject.get("access_token"); accessTokenExpiryInSeconds = authenticatedJsonResponseObject.get("expires_in"); print "accessToken:"+str(accessToken); print "accessTokenExpiryInSeconds:"+str(accessTokenExpiryInSeconds); return dict({"accessToken": accessToken, "accessTokenExpiryInSeconds": accessTokenExpiryInSeconds})
def getFirefox(): try: driver = FirefoxDriver() except: driver = None; return driver
import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class SSLExample { private WebDriver driver; @BeforeClass public void setUp() { //Creating new Firefox profile FirefoxProfile profile = new FirefoxProfile(); profile.setAcceptUntrustedCertificates(true); profile.setAssumeUntrustedCertificateIssuer(false); driver = new FirefoxDriver(profile); driver.manage().window().maximize(); } @Test public void openApplication() { System.out.println("Navigating application"); driver.get("https://cacert.org/"); WebElement headingEle = driver.findElement(By.cssSelector(".story h3")); //Validate heading after accepting untrusted connection String expectedHeading = "Are you new to CAcert?"; Assert.assertEquals(headingEle.getText(), expectedHeading); } @AfterClass public void tearDown() {