isDisplayed()方法用于确定元素是否可见。本文将详细讨论
的WebElement接口isDisplayed()方法。
下面突出显示的元素是一个可见元素。这种元素存在于我们Selenium游乐场网站上。我们将在这个元素上使用isDisplayed()方法,看看会发生什么。
public class CodekruTest { @Test public void test() { // pass the path of the chromedriver location in the second argument System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); WebDriver driver = new ChromeDriver(); // opening the url driver.get("https://testkru.com/Elements/TextMessages"); WebElement element = driver.findElement(By.id("plainText")); System.out.println("Is element visible on webpage: " + element.isDisplayed()); } }
产出-
Is element visible on webpage: true
我们可以在同一个网页上再次找到隐藏的元素(我们心爱的游乐场网站)。我们在下图中突出显示了隐藏的元素。
现在让我们在隐藏元素上使用isDisplayed()方法。
public class CodekruTest { @Test public void test() { // pass the path of the chromedriver location in the second argument System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); WebDriver driver = new ChromeDriver(); // opening the url driver.get("https://testkru.com/Elements/TextMessages"); WebElement element = driver.findElement(By.id("hiddenText")); System.out.println("Is element visible on webpage: " + element.isDisplayed()); } }
产出-
Is element visible on webpage: false
我们将得到一个NullPointerException,如下面的例子所示。
public class CodekruTest { @Test public void test() { // pass the path of the chromedriver location in the second argument System.setProperty("webdriver.chrome.driver", "C:\\Users\\MEHUL\\OneDrive\\Desktop\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); // opening the url driver.get("https://testkru.com/Elements/TextMessages"); WebElement element = null; System.out.println("Is element visible on webpage: " + element.isDisplayed()); } }
产出-
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.isDisplayed()" because "element" is null
下一篇:qq盗号为什么能改手机号