我得到的元素没有附加到上面代码的页面文档错误。此外,我想知道如何处理因目标页面上的操作而“出现”的元素。
WebDriver driver = new ChromeDriver();
driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf");
driver.manage().window().maximize();
driver.findElement(By.linkText("Sign up")).click();
//Verify whether the navigation is to the correct page
String title=driver.getTitle();
if (title.equals("IRCTC Next Generation eTicketing System")){
driver.findElement(By.id("userRegistrationForm:userName")).sendKeys("abcdef");
driver.findElement(By.linkText("Check Availability")).click();
WebElement text=driver.findElement(By.xpath(".//*[@id='userRegistrationForm:useravail']"));
boolean availability=text.isDisplayed();
try {if(availability==true){
System.out.println("The user id is available. Please enter other details to complete registration");
}}
catch (NoSuchElementException e){
System.out.println("The user id is not available. Please enter a different user ID.");
}
}
else
System.out.println("You are on a wrong page");
}
}
答案 0 :(得分:0)
您需要创建自定义等待来处理因操作而出现的元素。从技术上讲,你正在等待预期的条件成真。
private void waitForElement(String element) {
WebDriverWait wait = new WebDriverWait(Driver, 10); // Wait for 10 seconds.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));
WebElement element = driver.findElement(By.xpath(element));
element.click(); // The element is now present and can now be clicked
}
在上面的代码中,您知道元素的字符串/ xpath。您可以将其传递给此方法,并等待10秒钟以使execpected条件变为true。如果为true,则可以单击该元素。
答案 1 :(得分:0)
首选方法是使用.findElements()
(复数),然后检查为空,而不是捕获异常。如果集合为空,则该元素不存在于页面上。如果存在,请抓住.get(0)
并使用它。
我为您的代码添加了一些其他优化。我会做更像这样的事情。
driver.get("http://toolsqa.com/automation-practice-table/");
driver.findElement(By.linkText("Sign up")).click();
// Verify whether the navigation is to the correct page
if (driver.getTitle().equals("IRCTC Next Generation eTicketing System"))
{
driver.findElement(By.id("userRegistrationForm:userName")).sendKeys("abcdef");
driver.findElement(By.linkText("Check Availability")).click();
List<WebElement> text = driver.findElements(By.id("userRegistrationForm:useravail"));
if (!text.isEmpty())
{
// element found
if (text.get(0).isDisplayed())
{
System.out.println("The user id is available. Please enter other details to complete registration");
}
}
else
{
// element NOT found
System.out.println("The user id is not available. Please enter a different user ID.");
}
}
else
{
System.out.println("You are on a wrong page");
}
如果您执行某些操作然后需要等待元素显示,则可以使用WebDriverWait
。下面是一个示例,等待BUTTON
可见并点击它。
By buttonLocator = By.id("theButtonId");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(buttonLocator));
button.click();
ExpectedConditions
下有许多其他选项,您应该在链接的文档中查看。