在Selenium中通过文本查找元素是使用其文本属性来定位一个网络元素。当基本的元素识别属性(如ID或Class)是动态的,使其难以定位网络元素时,大多会使用文本值。
有时,开发者倾向于将具有相同ID或相同Class的类似Web元素组合在一起。例如,如果你有一个标签为Button的元素,它有一个动态的ID和Class名称,其中ID从 “ID-3465-text1 “变为 “ID-4434-textE2″,而Class名称在每个新会话中从 “ID-Class-text45 “变为 “ID-Class-text73″。
在这种情况下,使用ID或Class属性来定位网络元素变得非常困难,这时Text属性在执行Selenium自动化测试时就会发挥作用。
文本值可以完全匹配或部分匹配来定位元素。在这篇关于如何在Selenium WebDriver中通过文本查找元素的文章中,你将了解到如何使用Text属性来查找任何元素。
让我们开始吧!
什么是Selenium中的查找元素?
当你开始写你的Selenium自动化脚本时,与网络元素的交互成为你的第一步,也是非常重要的一步,因为你在测试脚本中玩的是WebElements。现在,只有当你用正确的方法来识别这些网络元素时,与它们的互动才能发生。
Selenium中的查找元素方法是一个帮助你识别网络元素的命令。查找元素有多种方法,可以使用Selenium中的Web定位器(如ID、Name、Class Name等)在网页中唯一地识别一个Web元素。下面是Selenium中查找元素的语法。
查找元素的语法是
WebElement elementName= driver.findElement(By.<LocatorStrategy>("LocatorValue"));
如上面的语法所示,该命令接受 “By“对象作为参数并返回一个WebElement对象。By“是一个定位器或查询对象,接受定位器策略。定位器策略可以有以下几种值。
- ID
- 名称
- 类别名称
- 标签名称
- 链接文本
- 部分链接文本
- XPath
- CSS选择器
什么是Selenium中通过文本查找元素?
我们在上一节中看到了Selenium中的查找元素和它的语法。现在,你一定想知道如何在Selenium WebDriver中通过文本查找元素。
答案是通过使用Selenium中的XPath!
想知道怎么做吗?让我们看看下面的部分。
为了使用文本,你需要使用XPath作为你的定位策略,并在定位值中使用元素的文本属性。
Selenium中XPath的基本格式如下。
XPath = //tagname[@Attribute=’Value’]
然而,在我们开始之前,有必要了解Selenium的两个内置方法,这两个方法最终将用于findElement。
- text() – 这是Selenium的一个内置方法,与XPath一起使用,以便根据一个元素的确切文本值来定位它。在findElement中使用text()的语法是。
WebElement ele = driver.findElement(By.xpath(“//<tagName>[text()=’text value’]”))
- contains()– 与text()方法类似,contains()是另一个内置方法,与XPath一起使用。然而,这是在我们想根据部分文本匹配来写定位器时使用的。在 findElement 中使用 text() 和 contains() 的语法是。
WebElement ele=driver.findElement(By.xpath(“//<tagName>[contains(text(),’textvalue’)]”))
现在让我们详细了解一下这些。
在Selenium中通过文本查找元素,用于完整的文本匹配
现在,你已经看到了在完全文本匹配的情况下使用text()的语法。在这一节中,关于如何在Selenium中通过文本查找元素,让我们通过一个例子来看看。
我们将使用LambdaTest提供的Selenium Playground来理解这一点。LambdaTest是一个基于云的跨浏览器测试平台,支持Selenium网格,为你使用本地机器进行自动化测试时面临的每一个障碍提供解决方案。像LambdaTest这样的测试自动化平台提供了一个由3000多个在线浏览器组成的Selenium网格,让你毫不费力地执行Selenium自动化测试。
使用案例
- 登录到Selenium Playground。
- 使用text()方法识别上述网页上的Checkbox Demo链接的Web元素。
- 点击它并打印页面标题。
实施
我们将使用Java的Selenium实现该案例,并使用LambdaTest提供的云Selenium网格来执行我们的测试案例。
Selenium网格是指一种软件测试设置,它使质量保证人员能够在多个浏览器和具有独特操作系统的设备上执行并行测试。当Selenium Grid的整个设置可以使用基于云的服务器访问时,它被称为Selenium Grid Cloud。一个在线的Selenium Grid帮助你专注于编写更好的Selenium测试脚本,而不是担心基础设施的维护。
现在让我们来检查一下复选框演示页面的定位器。为了检查,你可以简单地右键点击网络元素,然后点击检查。在元素标签上,你可以开始编写你的定位器。
如上图所示,我们使用Checkbox Demo文本与它的标签a进行完全匹配,因此,这里的正确实现将是。
WebElement checkbox= driver.findElement(By.xpath(“//a[text()=’Checkbox Demo’]”))
现在让我们使用同样的方法,写出我们的测试案例。
你可以参考下面的测试案例。
package LambdaTest;
import org.openqa.Selenium.By;
import org.openqa.Selenium.WebElement;
import org.openqa.Selenium.remote.DesiredCapabilities;
import org.openqa.Selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
@Listeners({util.Listener.class})
class AutomationUsingFindElementByText {
public String username = "YOUR USERNAME";
public String accesskey = "YOUR ACCESSKEY";
public static RemoteWebDriver driver = null;
public String gridURL = "@hub.lambdatest.com/wd/hub";
@BeforeTest
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "96.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
capabilities.setCapability("build", "AutomationUsingFindElement");
capabilities.setCapability("name", "AutomationUsingFindElementSuite");
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Test
public void findElementByCompleteTextMatch() {
try {
System.out.println("Logging into Lambda Test Selenium Playground");
driver.get("http://labs.lambdatest.com/Selenium-playground/");
WebElement checkBoxDemoPage= driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
checkBoxDemoPage.click();
System.out.println("Clicked on the Checkbox Demo Page");
WebElement header=driver.findElement(By.xpath("//h1"));
System.out.println("The header of the page is:"+header.getText());
} catch (Exception e) {
}
}
@AfterTest
public void closeBrowser() {
driver.close();
System.out.println("The driver has been closed.");
}
}
你可以使用下面的testng.xml文件来运行上述测试案例。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="AutomationUsingFindElementSuite">
<test name="AutomationUsingFindElementTest" >
<classes>
<class name="LambdaTest.AutomationUsingFindElementByText" >
</class>
</classes>
</test>
</suite>
下面的pom.xml文件用于安装所有必要的依赖项。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>LambdaTest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.Seleniumhq.Selenium</groupId>
<artifactId>Selenium-api</artifactId>
<version>4.0.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.Seleniumhq.Selenium</groupId>
<artifactId>Selenium-remote-driver</artifactId>
<version>4.0.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.Seleniumhq.Selenium</groupId>
<artifactId>Selenium-chrome-driver</artifactId>
<version>4.0.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>4.4.3</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
代码演练
在这个关于如何在Selenium中通过文本查找元素的部分,让我们详细看看代码的不同区域。
- 导入的依赖性。在这里,我们已经导入了Selenium WebDriver、WebDriverWait、Desired Capabilities和RemoteWebDriver的所有必要的类,以设置各自的浏览器能力并在网格上运行测试案例。
-
全局变量。由于我们使用了像LambdaTest这样的Selenium网格云来执行我们的测试,我们使用了下面的变量。
在这里,你可以填入相应的用户名和访问密钥的值,这些值可以通过登录LambdaTest配置文件部分收集。你可以复制用户名和访问令牌,以便在代码中使用。然而,网格的URL将保持不变,如下图所示。
我们在这里也使用了监听器类,以便定制TestNG报告。TestNG为我们提供了很多监听器(例如,IAnnotationTransformer,IReporter等)。这些接口在执行Selenium自动化测试时主要用于生成日志和定制TestNG报告。
为了实现监听器类,你可以简单地在你的测试类中添加一个注解,就在你的类名上面。
语法。
@Listeners(PackageName.ClassName.class)
- @BeforeTest(设置方法)。在这里,我们使用了LambdaTest DesiredCapabilities Generator,并为我们的Selenium Remote WebDriver设置了浏览器名称、版本、平台等必要的能力。之后,我们在启动的浏览器中打开网站。
- @Test(findElementByCompleteTextMatch)。在这种情况下,我们首先登录到Selenium Playground的网页。之后,我们使用完整的文本匹配找到Checkbox Demo按钮,并点击该按钮。最后,我们要打印网页的标题。
- @AfterTest(closeBrowser)。这里,我们只是关闭启动的浏览器。
一旦测试完成,你也可以在LambdaTest自动化仪表板上查看你的测试结果、日志和测试记录。
控制台输出
一旦你运行了测试用例,控制台的输出将看起来像下面这样。
下面的视频将帮助你通过与不同的网络元素互动,在Selenium中使用Java编写你的第一个测试脚本。
你也可以订阅LambdaTest YouTube频道,随时了解围绕Selenium测试、Cypress E2E测试、CI/CD等的最新教程。
在Selenium中通过文本查找元素,实现部分文本匹配
在本文关于如何在Selenium WebDriver中按文本查找元素的前一个例子中,你看到了如何使用findElement by Text来进行完整的文本匹配。在本节中,我们将了解如何使用部分文本匹配来定位网络元素。
同时阅读–在Selenium中用链接文本和部分链接文本查找元素
使用案例
- 登录到Selenium Playground。
- 识别所有名称中含有表格的网络元素。
- 打印所有这些Web元素的文本。
让我们看看上述测试案例的定位器。
实施
如上图所示,我们使用Table文本和它的标签a进行部分匹配,结果,我们使用上述定位器得到了总共5个Web元素。由于有超过1个的Web元素,在这种情况下,我们将使用FindElements。
Selenium中的FindElements会返回与定位器值相匹配的Web元素的列表,不像FindElement那样只返回一个Web元素。如果网页中没有匹配的元素,FindElements会返回一个空列表。
Selenium中FindElements的语法是。
List<WebElement> listName= driver.findElements(By.<LocatorStrategy>(“LocatorValue”))
因此,在这里使用部分文本匹配的FindElements的正确实现是。
List<WebElement> tableOptions=driver.findElements(By.xpath(“//a[contains(text(),’Table’)”)
现在让我们使用同样的方法来编写我们的测试案例。
你可以参考下面的测试案例。
package LambdaTest;
import org.openqa.Selenium.By;
import org.openqa.Selenium.WebElement;
import org.openqa.Selenium.remote.DesiredCapabilities;
import org.openqa.Selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
@Listeners({util.Listener.class})
class AutomationUsingFindElementByText {
public String username = "YOUR USERNAME";
public String accesskey = "YOUR ACCESSKEY";
public static RemoteWebDriver driver = null;
public String gridURL = "@hub.lambdatest.com/wd/hub";
@BeforeTest
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "96.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
capabilities.setCapability("build", "AutomationUsingFindElement");
capabilities.setCapability("name", "AutomationUsingFindElementSuite");
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Test
public void findElementByPartialTextMatch() {
try {
System.out.println("Logging into Lambda Test Selenium Playground");
driver.get("http://labs.lambdatest.com/Selenium-playground/");
List<WebElement> tableOptions= driver.findElements(By.xpath("//a[contains(text(),'Table')]"));
for(WebElement e: tableOptions){
System.out.println("The different options with table in name are:"+e.getText());
}
} catch (Exception e) {
}
}
@AfterTest
public void closeBrowser() {
driver.close();
System.out.println("The driver has been closed.");
}
}
你可以使用下面的testng.xml文件来运行上述测试案例。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="AutomationUsingFindElementSuite">
<test name="AutomationUsingFindElementTest" >
<classes>
<class name="LambdaTest.AutomationUsingFindElementByText" >
</class>
</classes>
</test>
</suite>
还有下面的pom.xml文件用于安装所有必要的依赖项。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>LambdaTest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.Seleniumhq.Selenium</groupId>
<artifactId>Selenium-api</artifactId>
<version>4.0.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.Seleniumhq.Selenium</groupId>
<artifactId>Selenium-remote-driver</artifactId>
<version>4.0.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.Seleniumhq.Selenium</groupId>
<artifactId>Selenium-chrome-driver</artifactId>
<version>4.0.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>4.4.3</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
代码演练
在这一节中,关于如何在Selenium中通过文本查找元素,现在让我们详细检查一下测试案例的演练。BeforeTest和import语句与我们在之前的例子中看到的保持一致。
@Test(findElementByPartialTextMatch)。在这种情况下,我们首先登录到Selenium Playground网页。之后,我们找到所有文本中含有Table的Web元素,并将其存储在一个列表中。之后,我们对该列表进行迭代,并打印其文本。
一旦测试完成,你也可以在LambdaTest自动化仪表板上查看你的测试结果、日志和测试记录。
你还可以在LambdaTest分析仪表板上看到测试结果。该仪表板显示与您的测试有关的所有细节和指标。
导航到LambdaTest分析仪表板以查看您的测试指标。您可以从测试概述中快速评估测试性能和整体健康状况。测试概述将显示你的团队运行了多少个通过和失败的测试以及这些测试的整体效率。
控制台输出
一旦你运行了测试用例,控制台的输出将看起来像下面这样。
如果你是一名开发人员或测试人员,并希望将你的技能提高到一个新的水平,LambdaTest的这个Selenium 101认证可以帮助你达到这个目标。
下面是LambdaTest的Selenium 101认证的一个简短介绍。
结论
在这个关于如何在Selenium WebDriver中通过文本查找元素的Selenium Java教程中,我们探讨了在Selenium中使用文本查找元素。我们看到,在完全和部分文本匹配的情况下,我们如何使用text()方法。我们还看到了如何在FindElements的情况下使用它,并通过文本匹配获得一个Web元素的列表。最后,我们还在云Selenium网格上用Java实现了这些案例。
说实话,当涉及到定位Web元素时,使用text()是我个人在Selenium中最喜欢的方法之一,因为它非常容易实现,而且可以以任何方式调整以符合我们的用例。
我希望你喜欢阅读这篇关于如何在Selenium中通过文本查找元素的文章,了解更多关于FindElement By Text的信息,我相信这个方法也会成为你个人的最爱。
测试愉快!
常见问题(FAQ)
如何在Selenium中搜索文本?
findElement “方法返回一个WebElement对象。这个对象有一个’getText’方法,它返回该元素上的可见文本。要找到一个特定的元素,使用’findElement’方法和适当的定位器。
什么是XPath中的text()?
在XPath中,text()是一个匹配文本节点的节点测试。文本节点是指当元素写在HTML源代码或XML源代码中时,在开始和结束标签之间包含文本的那种节点。
如何在Selenium中找到一个元素?
你可以使用以下方法。
- ID。
- 名称。
- ClassName。
- 标签名称。
- 链接文本/部分链接文本。
- CSS选择器。
- XPATH选择器。
暂无评论内容