如何在 Selenium 定位器中使用正则表达式?
我们可以在 Selenium webdriver 的定位器中使用正则表达式。这可以在我们使用 xpath 或 css 定位器识别元素时实现。让我们看一下元素在其 html 代码中的 class 属性。class 属性值为 **gsc-input**。

在这里,使用 css 表达式,我们可以使用 * 并对 class 属性值执行部分匹配。css 值应为 **input[class*='input']**。这意味着子文本 **input** 存在于实际文本 **gsc-input** 中。我们还可以使用 ^ 并对 class 执行匹配。css 值应为 **input[class^='gsc']**。这意味着实际文本 **gsc-input** 以子文本 gsc 开头。我们还可以使用 $ 并对 class 执行匹配。css 值应为 **input[class$='put']**。这意味着实际文本 **gsc-input** 以子文本 **put** 结尾。
在这里,使用 xpath 表达式,我们可以使用 **contains()** 方法并对 class 执行部分匹配。xpath 值应为 **//*[contains(@class, 'input')]**。这意味着子文本 **input** 存在于实际文本 **gsc-input** 中。我们还可以使用 **starts-with()** 并对 class 执行匹配。css 值应为 **//*[starts-with(@class, 'gsc')]**。这意味着实际文本 **gsc-input** 以子文本 **gsc** 开头。我们还可以使用 **ends-with()** 并对 class 执行匹配。css 值应为 **//*[ends-with(@class, 'put')]**。这意味着实际文本 **gsc-input** 以子文本 **put** 结尾。
示例
代码实现。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class RegexLocator{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify element with partial class match with * in css
WebElement l=driver.findElement(By.cssSelector("input[class*='input']"));
l.sendKeys("Selenium");
// obtain the value entered with getAttribute method
System.out.println("Using * expression: " +l.getAttribute("value"));
l.clear();
// identify element with partial class match with ^ in css
WebElement m=driver.findElement(By.cssSelector("input[class^='gsc']"));
m.sendKeys("Java");
// obtain the value entered with getAttribute method
System.out.println("Using ^ expression: " +m.getAttribute("value"));
m.clear();
// identify element with partial class match with $ in css
WebElement n = driver.findElement(By.cssSelector("input[class$='put']"));
n.sendKeys("Python");
// obtain the value entered with getAttribute method
System.out.println("Using $ expression: " +n.getAttribute("value"));
n.clear();
// identify element with partial class match with contains in xpath
WebElement o= driver.findElement(By.xpath("//input[contains(@class,'input')]"));
o.sendKeys("Selenium");
// obtain the value entered with getAttribute method
System.out.println("Using contains: " +o.getAttribute("value"));
o.clear();
// identify element with partial class match with starts-with in xpath
WebElement p= driver.findElement(By.xpath("//input[starts-with(@class,'gsc')]"));
p.sendKeys("Java");
// obtain the value entered with getAttribute method
System.out.println("Using starts-with: " +p.getAttribute("value"));
p.clear();
driver.close();
}
}输出

数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP