Java 验证按钮是否可见
我有一个测试脚本,它基本上为不同的用户逐步完成了许多步骤。一些用户将看到特定的按钮,而其他用户则不会看到 我创建了一个方法,用于检查按钮是否显示以下内容:Java 验证按钮是否可见,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我有一个测试脚本,它基本上为不同的用户逐步完成了许多步骤。一些用户将看到特定的按钮,而其他用户则不会看到 我创建了一个方法,用于检查按钮是否显示以下内容: public boolean check_create_new_item_button_visible(){ Boolean visible = driver.findElement(By.linkText("New Item")).isDisplayed(); return visible; } 并按以下方式调用: b
public boolean check_create_new_item_button_visible(){
Boolean visible = driver.findElement(By.linkText("New Item")).isDisplayed();
return visible;
}
并按以下方式调用:
boolean visible = npc.check_create_new_item_button_visible();
但我总是犯错误:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"link text","selector":"New Item"}
这正是您所期望的,因为按钮不可见
这可能是一个愚蠢的错误,但我如何才能得到它,找出按钮是否在屏幕上,以便我的程序可以继续
顺便说一句,我将代码移动到程序的一部分,其中按钮可见,布尔可见返回true。因此,如果按钮可见,代码就会工作。如果
driver.findelelement
找到该元素,则返回该元素;如果找不到该元素,则抛出NoTouchElementException
。为了避免异常,您可以使用findElements
检查返回的列表是否包含元素,如果包含元素,则检查第一个元素是否可见
public boolean check_create_new_item_button_visible() {
List<WebElement> buttons = driver.findElements(By.linkText("New Item"));
if (buttons.size() > 0 && buttons.get(0).isDisplayed())
{
return true;
}
return false;
}
public boolean check\u create\u new\u item\u button\u visible(){
列表按钮=driver.findElements(By.linkText(“新项”);
if(buttons.size()>0&&buttons.get(0.isDisplayed())
{
返回true;
}
返回false;
}
你能分享你的html
抱歉@narendrajput我不知道如何将html代码粘贴到这里谢谢你的快速回复@Guy我试用了你的代码,效果很好!今天我学到了一些东西,感谢@Samir007,我也尝试了你的代码,但它不太管用,所以我对它进行了如下修改以使其正常工作。我也喜欢你的解决方案。谢谢<代码>公共布尔检查\u创建\u新建\u项目\u按钮\u可见(){try{WebElement button=driver.findelelement(By.linkText(“新项目”);if(button.isDisplayed()){return true;}catch(org.openqa.selenium.NoSuchElementException e){System.out.println(“未找到元素”);返回false;}返回false;}谢谢@tarquin您想让我更新代码吗?它起作用了,所以我觉得很好
public boolean check_create_new_item_button_visible(){
try {
boolean btnPresence = driver.findElement(By.linkText("New Item")).isDisplayed();
boolean btnEnable = driver.findElement(By.linkText("New Item")).isEnabled();
if (btnPresence ==true && btnEnable ==true)
{
// click on the search button
WebElement btn = driver.findElement(By.linkText("New Item"));
btn .click();
}
catch (org.openqa.selenium.NoSuchElementException e){
return false;
}
}