如何在selenium webdriver中运行时获取实时定位器

时间:2018-02-06 05:27:00

标签: java selenium xpath selenium-webdriver ui-automation

我正在自动化包含某些操作的网页,但这些操作元素经常被更改,从而导致异常。有没有办法在运行时获取实时元素或selenium webdriver中的任何其他解决方案?

环境:Eclipse phone m4Java 8Selenium Webdriver 3.8.1Chrome 64Windows 8

代码段:

driver.get("https://www.qcommission.com");
driver.switchTo().frame("60343815682962");
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(".//*[@id='header_42']"), "Demo Inquiry"));
Thread.sleep(2000);
driver.findElement(By.id("input_24")).clear();
driver.findElement(By.id("input_24")).sendKeys(name);
driver.findElement(By.id("input_16")).clear();
driver.findElement(By.id("input_16")).sendKeys(emailjoin);
driver.findElement(By.id("input_50")).clear();
driver.findElement(By.id("input_50")).sendKeys(count_of_payee);
driver.findElement(By.id("input_51_full")).clear();
driver.findElement(By.id("input_51_full")).sendKeys(phone_number);
driver.findElement(By.id("input_48")).click();
driver.switchTo().defaultContent();
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thread.sleep(50000);

if(driver.getPageSource().contains("Thank you for your inquiry!"))
{
    System.out.println("PASS - Demo Inquiry");
    driver.close();
    driver.quit();
}
else
{
    System.out.println("FAIL - Demo Inquiry");

    driver.close();
    driver.quit();
}

1 个答案:

答案 0 :(得分:0)

您可以使用XPath代替id,而不是id:

对于文字字段

名称:

driver.findElement(By.xpath("//label[contains(text(), 'Name')]/../*/input")).clear();
driver.findElement(By.xpath("//label[contains(text(), 'Name')]/../*/input")).sendKeys(name);

用于电子邮件下方的文字字段:

driver.findElement(By.xpath("//label[contains(text(), 'E-mail')]/../*/input")).clear();
driver.findElement(By.xpath("//label[contains(text(), 'E-mail')]/../*/input")).sendKeys(name);

适用于收款人数下方的文字字段:

driver.findElement(By.xpath("//label[contains(text(), 'Count of Payees')]/../*/input")).clear();
driver.findElement(By.xpath("//label[contains(text(), 'Count of Payees')]/../*/input")).sendKeys(name);

用于电话号码下方的文字字段:

driver.findElement(By.xpath("//label[contains(text(), 'Phone Number')]/../div/span/input")).clear();
driver.findElement(By.xpath("//label[contains(text(), 'Phone Number')]/../div/span/input")).sendKeys(name);

检查是否有帮助:)