Selenium WebDriver 的 isDisplayed() 方法如何工作?
seleniumautomation testingtesting tools更新于 2026/2/11 11:37:17
我们可以在 Selenium WebDriver 中使用 isDisplayed() 方法。此方法检查 Web 元素在页面上是否可见。如果可见,则返回 true,否则返回 false。
首先,我们必须使用定位器(例如 id、class、name、xpath 或 css)来识别元素,然后对其应用 isDisplayed() 方法。
语法
boolean s= driver.findElement(By.id("txt-bx")).isDisplayed();
让我们检查元素 About Careers at Tutorials Point 是否显示在页面上。因为它可用,所以它应该返回一个真实值。

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class VisibleElement{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// 识别元素
WebElement p=driver.findElement(By.xpath("//h1"));
//isDisplayed() 检查元素是否可见
boolean s= p.isDisplayed();
System.out.println("The return value: " + s);
driver.close();
}
}
输出

相关文章
打印
下一节:如何使用 Java 的 Selenium WebDriver 获取父 HTML 标签? ❯❮ 上一节:如何在 Selenium Webdriver 2 Python 中获取当前 URL?

