org.openqa.selenium.WebDriver.findElement()方法的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(12.8k)|赞(0)|评价(0)|浏览(105)

本文整理了Java中org.openqa.selenium.WebDriver.findElement()方法的一些代码示例,展示了WebDriver.findElement()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WebDriver.findElement()方法的具体详情如下:
包路径:org.openqa.selenium.WebDriver
类名称:WebDriver
方法名:findElement

WebDriver.findElement介绍

[英]Find the first WebElement using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached. findElement should not be used to look for non-present elements, use #findElements(By)and assert zero length response instead.
[中]使用给定的方法查找第一个WebElement。此方法受执行时有效的“隐式等待”时间的影响。findElement(…)调用将返回匹配的行,或重复尝试,直到达到配置的超时。findElement不应用于查找不存在的元素,而应使用#findElements(By)并断言零长度响应。

代码示例

代码示例来源:origin: stackoverflow.com

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementsByName('body')[0].setAttribute('type', 'text');");
driver.findElement(By.xpath("//input[@name='body']")).clear();
driver.findElement(By.xpath("//input[@name='body']")).sendKeys("Ripon: body text");

代码示例来源:origin: stackoverflow.com

WebElement getStaleElem(By by, WebDriver driver) {
  try {
    return driver.findElement(by);
  } catch (StaleElementReferenceException | NoSuchElementException e) {
    System.out.println("Attempting to recover from " + e.getClass().getSimpleName() + "...");
    return getStaleElem(by, driver);
  }
}

代码示例来源:origin: apache/geode

private void login() {
 WebElement userNameElement = waitForElementById("user_name", 60);
 WebElement passwordElement = waitForElementById("user_password");
 userNameElement.sendKeys(username);
 passwordElement.sendKeys(password);
 passwordElement.submit();
 driver.get(getPulseURL() + "clusterDetail.html");
 WebElement userNameOnPulsePage =
   (new WebDriverWait(driver, 30, 1000)).until(
     (ExpectedCondition<WebElement>) d -> d.findElement(By.id("userName")));
 assertNotNull(userNameOnPulsePage);
}

代码示例来源:origin: cloudfoundry/uaa

private void performLogin(String username) {
  webDriver.get(zoneUrl + "/logout.do");
  webDriver.manage().deleteAllCookies();
  webDriver.get(zoneUrl + "/login");
  webDriver.findElement(By.name("username")).sendKeys(username);
  webDriver.findElement(By.name("password")).sendKeys(USER_PASSWORD);
  webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
}

代码示例来源:origin: stackoverflow.com

WebDriver driver = new FirefoxDriver();
     driver.get("http://www.reddit.com/r/pics/");
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     WebElement element = driver.findElement(By
         .linkText("next ›"));
     element.click();
     System.out.println(driver.getCurrentUrl());

代码示例来源:origin: ksahin/introWebScraping

public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
  System.setProperty("phantomjs.page.settings.userAgent", USER_AGENT);
  String baseUrl = "https://www.inshorts.com/en/read" ;
  initPhantomJS();
  driver.get(baseUrl) ;
  int nbArticlesBefore = driver.findElements(By.xpath("//div[@class='card-stack']/div")).size();
  driver.findElement(By.id("load-more-btn")).click();
  
  WebDriverWait wait = new WebDriverWait(driver, 30);
  // We wait for the ajax call to fire and to load the response into the page
  Thread.sleep(800);
  int nbArticlesAfter = driver.findElements(By.xpath("//div[@class='card-stack']/div")).size();
  System.out.println(String.format("Initial articles : %s Articles after clicking : %s", nbArticlesBefore, nbArticlesAfter));
}

代码示例来源:origin: org.juzu/juzu-core

@Test
 @RunAsClient
 public void test() throws Exception {
  driver.get(applicationURL().toString());
  System.out.println(driver.getPageSource());
  WebDriverWait wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html[@bar]")));
  WebElement elt = driver.findElement(By.tagName("html"));
  assertEquals("<bar>foo_value</bar>", elt.getAttribute("bar"));
 }
}

代码示例来源:origin: stackoverflow.com

Class<?> cls = Class.forName("org.openqa.selenium.firefox.FirefoxDriver");
WebDriver driver = (WebDriver) cls.newInstance();
driver.get("http://naukri.com");
WebElement webElement = driver.findElement(By.xpath("//div[@id='skill']"));
System.out.println(webElement.isEnabled());

代码示例来源:origin: cloudfoundry/uaa

private String startCreateUserFlow(String secret) {
  String userEmail = "user" + new SecureRandom().nextInt() + "@example.com";
  webDriver.get(baseUrl + "/");
  webDriver.findElement(By.xpath("//*[text()='Create account']")).click();
  assertEquals("Create your account", webDriver.findElement(By.tagName("h1")).getText());
  webDriver.findElement(By.name("email")).sendKeys(userEmail);
  webDriver.findElement(By.name("password")).sendKeys(secret);
  webDriver.findElement(By.name("password_confirmation")).sendKeys(secret);
  webDriver.findElement(By.xpath("//input[@value='Send activation link']")).click();
  return userEmail;
}

代码示例来源:origin: cloudfoundry/uaa

private void beginPasswordReset(String username) {
  webDriver.get(baseUrl + "/login");
  Assert.assertEquals("Cloud Foundry", webDriver.getTitle());
  webDriver.findElement(By.linkText("Reset password")).click();
  Assert.assertEquals("Reset Password", webDriver.findElement(By.tagName("h1")).getText());
  // Enter email address
  webDriver.findElement(By.name("username")).sendKeys(username);
  webDriver.findElement(By.xpath("//input[@value='Send reset password link']")).click();
  Assert.assertEquals("Instructions Sent", webDriver.findElement(By.tagName("h1")).getText());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testQRCodeValidation() {
  performLogin(username);
  assertEquals(zoneUrl + "/login/mfa/register", webDriver.getCurrentUrl());
  webDriver.findElement(By.id("Next")).click();
  assertEquals(zoneUrl + "/login/mfa/verify", webDriver.getCurrentUrl());
  webDriver.findElement(By.name("code")).sendKeys("1111111111111111112222");
  webDriver.findElement(By.id("verify_code_btn")).click();
  assertEquals("Incorrect code, please try again.", webDriver.findElement(By.cssSelector("form .error-color")).getText());
}

代码示例来源:origin: code4craft/webmagic

webDriver.get(request.getUrl());
try {
  Thread.sleep(sleepTime);
  e.printStackTrace();
WebDriver.Options manage = webDriver.manage();
Site site = task.getSite();
if (site.getCookies() != null) {
WebElement webElement = webDriver.findElement(By.xpath("/html"));
String content = webElement.getAttribute("outerHTML");
Page page = new Page();

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testPasscodeRedirect() throws Exception {
  webDriver.get(baseUrl + "/passcode");
  assertEquals("Cloud Foundry", webDriver.getTitle());
  attemptLogin(testAccounts.getUserName(), testAccounts.getPassword());
  assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), Matchers.containsString("Temporary Authentication Code"));
}

代码示例来源:origin: cloudfoundry/uaa

private void signIn(String userName, String password) {
    webDriver.findElement(By.name("username")).sendKeys(userName);
    webDriver.findElement(By.name("password")).sendKeys(password);
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
  }
}

代码示例来源:origin: cloudfoundry/uaa

private void finishPasswordReset(String username, String email) {
  String link = getPasswordResetLink(email);
  webDriver.get(link);
  // Successfully choose password
  webDriver.findElement(By.name("password")).sendKeys("newsecr3T");
  webDriver.findElement(By.name("password_confirmation")).sendKeys("newsecr3T");
  webDriver.findElement(By.xpath("//input[@value='Create new password']")).click();
  assertThat(webDriver.getCurrentUrl(), is(baseUrl + "/login?success=password_reset"));
  webDriver.findElement(By.name("username")).sendKeys(username);
  webDriver.findElement(By.name("password")).sendKeys("newsecr3T");
  webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
  assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?"));
}

代码示例来源:origin: stackoverflow.com

WebElement getStaleElem(By by, WebDriver driver) {
  try {
    return driver.findElement(by);
  } catch (StaleElementReferenceException e) {
    System.out.println("Attempting to recover from StaleElementReferenceException ...");
    return getStaleElem(by, driver);
  } catch (NoSuchElementException ele) {
    System.out.println("Attempting to recover from NoSuchElementException ...");
    return getStaleElem(by, driver);
  }
}

代码示例来源:origin: cloudfoundry/uaa

private void signIn(String userName, String password) {
    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(baseUrl + "/login");
    webDriver.findElement(By.name("username")).sendKeys(userName);
    webDriver.findElement(By.name("password")).sendKeys(password);
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?"));
  }
}

代码示例来源:origin: cloudfoundry/uaa

private void login(IdentityProvider<SamlIdentityProviderDefinition> provider) {
    webDriver.get(baseUrl + "/login");
    Assert.assertEquals("Cloud Foundry", webDriver.getTitle());
    webDriver.findElement(By.xpath("//a[text()='" + provider.getConfig().getLinkText() + "']")).click();
    webDriver.findElement(By.xpath("//h2[contains(text(), 'Enter your username and password')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName());
    webDriver.findElement(By.name("password")).sendKeys(testAccounts.getPassword());
    webDriver.findElement(By.xpath("//input[@value='Login']")).click();
  }
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testQRCodeScreen() throws Exception {
  performLogin(username);
  assertEquals(zoneUrl + "/login/mfa/register", webDriver.getCurrentUrl());
  String imageSrc = webDriver.findElement(By.id("qr")).getAttribute("src");
  String secretKey = getSecretFromQrImageString(imageSrc);
  webDriver.findElement(By.id("Next")).click();
  verifyCodeOnRegistration(secretKey, "/");
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testBannerFunctionalityInDiscoveryPage() {
  String zoneId = "testzone3";
  RestTemplate identityClient = IntegrationTestUtils.getClientCredentialsTemplate(
    IntegrationTestUtils.getClientCredentialsResource(baseUrl, new String[]{"zones.write", "zones.read", "scim.zones"}, "identity", "identitysecret")
  );
  IdentityZoneConfiguration config = new IdentityZoneConfiguration();
  config.setIdpDiscoveryEnabled(true);
  Banner banner = new Banner();
  banner.setText("test banner");
  banner.setBackgroundColor("#444");
  banner.setTextColor("#111");
  config.setBranding(new BrandingInformation());
  config.getBranding().setBanner(banner);
  IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId, zoneId, config);
  String zoneUrl = baseUrl.replace("localhost",zoneId+".localhost");
  webDriver.get(zoneUrl);
  webDriver.manage().deleteAllCookies();
  webDriver.navigate().refresh();
  assertEquals("test banner", webDriver.findElement(By.cssSelector(".banner-header span")).getText());
  assertEquals("rgba(68, 68, 68, 1)", webDriver.findElement(By.cssSelector(".banner-header")).getCssValue("background-color"));
  assertEquals("rgba(17, 17, 17, 1)", webDriver.findElement(By.cssSelector(".banner-header span")).getCssValue("color"));
  String base64Val = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATBJREFUeNqk008og3Ecx/HNnrJSu63kIC5qKRe7KeUiOSulTHJUTrsr0y5ycFaEgyQXElvt5KDYwU0uO2hSUy4KoR7v7/qsfmjPHvzq1e/XU8/39/3zPFHf9yP/WV7jED24nGRbxDFWUAsToM05zyKFLG60d/wmQBxWzwyOlMU1phELEyCmtPeRQRoVbKOM0VYB6q0QW+3IYQpJFFDEYFCAiMqwNY857Ko3SxjGBTbRXb+xMUamcMbWh148YwJvOHSCdyqTAdxZo72ADGwKT98C9CChcxUPQSVYLz50toae4Fy9WcAISl7AiN/RhS1N5RV5rOLxx5eom90pvGAI/VjHMm6bfspK18a1gXvsqM41XDVL052C1Tim56cYd/rR+mdSrXGluxfm5S8Z/HV9CjAAvQZLXoa5mpgAAAAASUVORK5CYII=";
  banner.setLogo(base64Val);
  IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId, zoneId, config);
  webDriver.get(zoneUrl);
  assertEquals("data:image/png;base64," + base64Val, webDriver.findElement(By.cssSelector(".banner-header img")).getAttribute("src"));
  assertEquals(2, webDriver.findElement(By.cssSelector(".banner-header")).findElements(By.xpath(".//*")).size());
}

相关文章