如何在 Selenium 中根据页面上可见的文本识别元素?
software testingautomation testingselenium web driver
要根据页面上可见的文本识别元素,可以使用 XPath 中的 text() 方法。
语法 −
driver.findElement(By.xpath("//tagname[text()=’value’]"))
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextMatch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// 使用 text() 方法的 xpath
driver.findElement(By.xpath("//*[text()=’GATE Exams’]")).click();
driver.close();
}
}

