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()))
WebDriver driver; @Before public void SetUp() { driver = new FirefoxDriver(); driver.manage().window().maximize(); // Navegamos hasta la aplicacion driver.get("http://demo.magentocommerce.com/"); } @Test public void testSearchByCategory() { // Creamos el WebElement Search Field WebElement searchField = driver.findElement(By.id("search")); // Introducimos la busqueda searchField.sendKeys("phones"); // realizamos la busqueda searchField.submit(); //driver.findElement(By.className("search-button")).click(); // Capturamos todos los elementos que devuelve la busqueda List<WebElement> products = driver.findElements(By.cssSelector(".product-name a")); // validamos el resultado assert products.size() == 2; }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Underwritemethod { private Logger logger = LogManager.getLogger( Underwritemethod. class ); private WaitTime waittime=new WaitTime(); private Checkelement checkelement=new Checkelement(); private GetElement getelement=new GetElement(); //校验区间分布模块 public void IntervalDistribution(WebDriver driver) { //等待饼图图出现 try{ checkelement.Waitelement(driver,20,By.xpath("//*[@id='item0']/div[1]/div[1]/div[1]/canvas")); waittime.sleepNumSeconds(1); driver.findElement(By.xpath("//*[@id='item0']/div[1]/div[1]/div[1]/canvas")).click(); //action.moveToElement(canvas.perform(); //等待饼图加载为100% checkelement.WaitelementContainstext(driver, 20, By.xpath("//*[@id='item0']/div[1]/div[1]/div[2]"), "100%"); logger.info("饼图加载完成"); } catch(Exception e){ logger.error("饼图未加载"); driver.quit(); } waittime.sleepNumSeconds(2); }
def test(): device[0].logInfo('This is Hello World!') device[0].getWebDriver().findElement(By.xpath("//input[@name='hphm']")).sendKeys("1234")
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})
WebDriver driver; @Given("^I am on the home page$") public void i_am_on_the_home_page() { WebDriverManager.chromedriver().setup(); System.out.println("I am going to www.tesla.com"); driver = new ChromeDriver(); driver.get("https://www.tesla.com/"); } @When("^I click on the model S link$") public void i_click_on_the_model_S_link() { System.out.println("clicking on the model S link"); driver.findElement(By.linkText("MODEL S")).click(); ; } @Then("^Model S homepage should be displayed$") public void model_S_homepage_should_be_displayed() { System.out.println("Verifying the Model S home Page"); assertTrue(driver.getTitle().contains("Model S")); System.out.println(driver.getTitle()+"------------------"); } }
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class DropDownCommands { public static void main(String[] args) throws InterruptedException { // Create a new instance of the FireFox driver WebDriver driver = new FirefoxDriver(); // Put an Implicit wait, driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch the URL driver.get("http://toolsqa.com/automation-practice-form"); // Step 3: Select 'Continents' Drop down ( Use Id to identify the element ) // Find Select element of "Single selection" using ID locator. Select oSelect = new Select(driver.findElement(By.id("continents"))); // Step 4:) Select option 'Europe' (Use selectByIndex) oSelect.selectByVisibleText("Europe"); // Using sleep command so that changes can be noticed Thread.sleep(2000); // Step 5: Select option 'Africa' now (Use selectByVisibleText) oSelect.selectByIndex(2); Thread.sleep(2000); // Step 6: Print all the options for the selected drop down and select one option of your choice // Get the size of the Select element List<WebElement> oSize = oSelect.getOptions(); int iListSize = oSize.size();
import org.openqa.selenium.chrome.ChromeDriverService; public class Confirm_Box { public static void main(String[] args) throws NoAlertPresentException, InterruptedException { System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true"); System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\driver\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Alert Message handling driver.get("http://localhost:5000/easytesting"); driver.findElement(By.id("btnk")).click(); // Switching to Alert Alert alert = driver.switchTo().alert(); // Capturing alert message. String alertMessage = alert.getText(); // Displaying alert message System.out.println(alertMessage); Thread.sleep(5000); // Accepting alert alert.accept(); } }
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() { if(driver!=null) driver.quit(); } }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.*; public class Form { public static void main(String[] args) { // declaration and instantiation of objects/variables System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String baseUrl = "http://demo.guru99.com/test/login.html"; driver.get(baseUrl); // Get the WebElement corresponding to the Email Address(TextField) WebElement email = driver.findElement(By.id("email")); // Get the WebElement corresponding to the Password Field WebElement password = driver.findElement(By.name("passwd")); email.sendKeys("*****@*****.**"); password.sendKeys("abcdefghlkjl"); System.out.println("Text Field Set"); // Deleting values in the text box email.clear(); password.clear(); System.out.println("Text Field Cleared"); // Find the submit button WebElement login = driver.findElement(By.id("SubmitLogin"));