网页可以包含许多Web元素或GUI元素,例如单选按钮,文本框,下拉菜单,输入等。Selenium自动化测试中的Web定位器用于对页面的Web元素执行不同的操作。 毫不奇怪,作为新的Selenium用户,我们要学习的第一件事是Selenium Locators。
这些定位器是任何Selenium自动化测试框架的基础,无论您进行的测试类型是什么,从单元测试到端到端自动化跨浏览器测试。 使用了多种类型的定位器,例如CSS选择器,XPath,链接,文本,ID等。这是一些用于自动跨浏览器测试的流行定位器。 到目前为止,您可以在Selenium中获得8种类型的定位器。 但是,这个数字将在新的Selenium 4版本中更改。 想知道为什么吗?
好吧,使用Selenium 3.0,每个元素都可以单独访问,因为无法访问相对于附近元素的Web元素。 在这里,Selenium 4(Alpha)中的新定位器可以发挥作用,因为新的定位器方法使您可以基于相对于DOM中其他元素的可见位置来查找附近的元素。
是的! 你没听错。 Selenium 4将推出一个已经计划了很长时间的新定位器,现在称为相对定位器。 在本文中,我们将深入探讨如何使用最新的Selenium 4 Relative Locator进行日常自动化测试。
我们在之前的文章中介绍了Selenium 4可以提供的功能 。 在该帖子本身中,我们暗示我们将在新功能方面进行更多详细说明。 好吧,这是。
下载硒4(Alpha)
毋庸置疑,最常用的Web自动化测试框架Selenium具有特殊的特殊功能,可广泛用于端到端测试,这些功能可提供无与伦比的自动化跨浏览器测试功能。 但是,最近的主要数字版本(即Selenium 3.0)已于3年前于2016年10月发布。尽管目前尚无发布日期,并且Selenium 4尚未正式发布,但您可以通过Selenium 4的Alpha进行先睹为快释放。
首先,您必须从Maven存储库下载Selenium 4 Alpha。 在作为本文的一部分介绍Selenium 4相对定位器功能时,最新版本是4.0.0-alpha-3。 由于这是Selenium的Alpha版本,因此,如果您不想在通过Selenium自动化测试进行验证时使用生产测试套件承担任何风险,建议您切换回稳定版本,即3.141.XX。
Selenium 4相对定位器–方法
到目前为止,Selenium 4相对定位器方法支持withTagName属性的使用。 以下是可在Selenium自动化测试中使用的“相对定位器”选项:
相对定位器 | 描述 |
---|---|
以上 | 要搜索/定位的Web元素显示在指定元素的上方。 |
下面 | 要搜索/定位的Web元素显示在指定元素的下方。 |
toLeftOf | 要搜索/定位的Web元素显示在指定元素的左侧。 |
toRightOf | 要搜索/定位的Web元素显示在指定元素的右侧。 |
近 | 要搜索/定位的Web元素距离指定元素最多50个像素。 |
这是该实现的屏幕截图,着重介绍了Selenium自动化测试中相对定位器的用法( Source )。
如果您想知道Selenium是如何做到这一点的,那么可以借助名为getBoundingClientRect( )JavaScript方法来实现。 此JavaScript方法允许Selenium使用相对定位器进行Selenium测试来定位元素。
Selenium 4相对定位器–用法
Selenium 4中用于相对定位器的方法已重载,可以将相对WebElement或“按”定位器作为参数。 下面显示的是使用这两个选项进行Selenium自动化测试的相对定位器的示例用法:
WebElement txt_label = driver.findElement(By.cssSelector("label[id='uname']"));
WebElement txt_label = driver.findElement(withTagName("input").toRightOf(txt_label));
String txt_name = driver.findElement(withTagName("input").toLeftOf(By.id("some_button"))
使用相对定位器执行硒自动化测试
让我们开始使用新的Selenium 4 Relative Locator进行自动跨浏览器测试 。 我将与本地Chrome WebDriver一起试用Selenium 4(Alpha)。 但是在此之前,我将创建一个用于实施和测试的Maven项目。 我将使用TestNG框架,因为它可以轻松地与Maven集成。 另外,由于内置的注释(例如@ BeforeClass,@ AfterClass,@ Test等),可以为触发的自动化测试提供更多的清晰度。
对于将进一步演示的两个测试,应使用项目配置[包括Selenium 4(Alpha)]更新Maven项目的项目对象模型(pom.xml)文件。
<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>Group-Name</groupId>
<artifactId>Artifact-Name</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>10</source>
<target>10</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-3</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.0.0</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.28</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
示例1对于硒4相对定位器
在演示Selenium 4相对定位符用法的第一个示例中,目的是使登录LambdaTest自动化。 由于测试是在Chrome浏览器上执行的,因此您应确保Chrome WebDriver在计算机上可用。
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class MavenRelocators {
private WebDriver driver;
boolean status = false;
@BeforeClass
public void setUp(){
System.setProperty("webdriver.chrome.driver","C:\\location-of-chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://accounts.lambdatest.com/login");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass
public void tearDown() throws Exception {
if (driver != null) {
driver.quit();
}
}
@Test
public void test_login_using_relative_locators_1(){
// Find the label element above the login text box
WebElement heightLabel = driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/h1"));
// Locate the textbox where username should be inputted
WebElement heightUserBox = driver.findElement(withTagName("input")
.below(heightLabel));
heightUserBox.sendKeys("user-name");
// Locate the textbox where password should be inputted
WebElement heightPasswordBox = driver.findElement(withTagName("input")
.below(heightUserBox));
heightPasswordBox.sendKeys("password");
// Locate the submit button
WebElement submitbutton = driver.findElement(By.xpath("//*[@id=\'app\']/section/form/div/div/button"));
submitbutton.click();
//Wait for 10 seconds to observe the output
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
查找必须输入用户名(例如电子邮件地址)的输入字段; 我们首先使用By.xpath方法在输入框上方找到标签。 要获取Web元素(例如XPath)的详细信息,您应该在Chrome浏览器中使用Inspect选项。
代码演练:
WebElement heightUserBox = driver.findElement(withTagName("input")
从上面的语句可以看出,FindElement方法的输入参数是withTagName。 成功执行后,它将返回RelativeLocator.RelativeBy对象。 输出将相对于WebElement heightLabel。
我们使用定位的元素来查找必须输入用户名的字段。 由于输入元素(用于用户名)位于标签的正下方,因此我们将使用以下选项以及withTagName()方法。
WebElement heightLabel = driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/h1"));
// Locate the textbox where username should be inputted
WebElement heightUserBox = driver.findElement(withTagName("input")
.below(heightLabel));
heightUserBox.sendKeys("user-name");
电子邮件输入框下方的Web元素是密码输入框。 由于电子邮件输入框的相对位置是已知的,因此以下选项可用于找到密码输入框。
WebElement heightPasswordBox = driver.findElement(withTagName("input")
.below(heightUserBox));
heightPasswordBox.sendKeys("password");
要执行测试,请右键单击该项目,然后选择选项“运行方式-> TestNG测试”。
示例2硒4相对定位器
在此示例中,演示了Selenium 4相对定位器的用法,目的是在LambdaTest Sample App中添加一个新条目。 它包含两个其他测试,在这两个测试中,所需的Web元素都位于该位置,并通过其属性(名称/ ID)进行验证。
package RelativeLocators;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class RelativeLocators {
private WebDriver driver;
boolean status = false;
@BeforeClass
public void setUp(){
System.setProperty("webdriver.chrome.driver","C:\\Location-To\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass
public void tearDown() throws Exception {
if (driver != null) {
driver.quit();
}
}
@Test
public void test_login_using_relative_locators_1(){
String name = driver.findElement(withTagName("input")
.above(By.name("li5"))
.below(By.name("li3")))
.getAttribute("name");
assertEquals(name, "li4");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void test_login_using_relative_locators_2(){
String txt_name = driver.findElement(withTagName("input")
.toLeftOf(By.id("addbutton"))
.below(By.name("li5")))
.getAttribute("id");
assertEquals(txt_name, "sampletodotext");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void test_login_using_relative_locators_3(){
WebElement txt_name = driver.findElement(withTagName("input")
.toLeftOf(By.id("addbutton"))
.below(By.name("li5")));
txt_name.sendKeys("Relative locators test");
// Get details of the Submit/Add button
WebElement submitbutton = driver.findElement(By.xpath("//*[@id=\'addbutton\']"));
// Submit the new entry
submitbutton.click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
让我们对包含三个不同测试的上述示例进行解码。 在进入任何测试的细节之前,重要的是我们先了解该应用程序的DOM代码段。
<ul class="list-unstyled">
<!-- ngRepeat: sampletodo in sampleList.sampletodos --><li ng-repeat="sampletodo in sampleList.sampletodos" class="ng-scope">
<input type="checkbox" ng-model="sampletodo.done" name="li1" class="ng-pristine ng-untouched ng-valid">
<span class="done-false">First Item</span>
</li><!-- end ngRepeat: sampletodo in sampleList.sampletodos --><li ng-repeat="sampletodo in sampleList.sampletodos" class="ng-scope">
<input type="checkbox" ng-model="sampletodo.done" name="li2" class="ng-pristine ng-untouched ng-valid">
<span class="done-false">Second Item</span>
</li><!-- end ngRepeat: sampletodo in sampleList.sampletodos --><li ng-repeat="sampletodo in sampleList.sampletodos" class="ng-scope">
<input type="checkbox" ng-model="sampletodo.done" name="li3" class="ng-pristine ng-untouched ng-valid">
<span class="done-false">Third Item</span>
</li><!-- end ngRepeat: sampletodo in sampleList.sampletodos --><li ng-repeat="sampletodo in sampleList.sampletodos" class="ng-scope">
<input type="checkbox" ng-model="sampletodo.done" name="li4" class="ng-pristine ng-untouched ng-valid">
<span class="done-false">Fourth Item</span>
</li><!-- end ngRepeat: sampletodo in sampleList.sampletodos --><li ng-repeat="sampletodo in sampleList.sampletodos" class="ng-scope">
<input type="checkbox" ng-model="sampletodo.done" name="li5" class="ng-pristine ng-untouched ng-valid">
<span class="done-false">Fifth Item</span>
</li><!-- end ngRepeat: sampletodo in sampleList.sampletodos -->
</ul>
DOM中的第五项在DOM中以名称li5表示,第三元素由名称li3表示。
子测试1 –在第一个测试中,必须找到名称为li4的元素,并在出现错误的情况下引发assert。 使用withTagName方法调用findElement方法,并输入TagName。 从下面的DOM树和Inspect屏幕截图可以看出,每个CheckBox的输入类型均与输入选项对应,即li1,li2,li3等。
名称为li4(第四项)的输入Web元素在li3(第三项)之上和li5(第五项)之下。 因此,我们将两者都指定为测试的一部分。
@Test
public void test_login_using_relative_locators_1(){
String name = driver.findElement(withTagName("input")
.above(By.name("li5"))
.below(By.name("li3")))
.getAttribute("name");
assertEquals(name, "li4");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
子测试2 –在此测试中,必须找到名称为sampletodotext的输入元素。 此元素为输入类型,位于“添加按钮”的左侧,即id = addbutton并位于名称为li5(第五项)的元素下方。
@Test
public void test_login_using_relative_locators_2(){
String txt_name = driver.findElement(withTagName("input")
.toLeftOf(By.id("addbutton"))
.below(By.name("li5")))
.getAttribute("id");
assertEquals(txt_name, "sampletodotext");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
如果元素的名称(即txt_name)与预期的名称(即sampletodotext)不匹配,则会引发断言。
子测试3 –此测试是子测试2的逻辑扩展,在子测试2中,必须将新项目/选项添加到lambdasampleapp。
为此,请在id = addbutton [.toLeftOf(By.id("addbutton")]
及以下name = li5 [.below(By.name("li5"))]
id = addbutton [.toLeftOf(By.id("addbutton")]
的元素下方,在元素左侧输入WebElement。 name = li5 [.below(By.name("li5"))]
必须位于。
由于输入元素是文本框,因此sendKeys方法用于在文本框中输入值,即id = sampletodotext。 通过单击页面上的“添加”按钮,将新选项添加到列表中。
@Test
public void test_login_using_relative_locators_3(){
WebElement txt_name = driver.findElement(withTagName("input")
.toLeftOf(By.id("addbutton"))
.below(By.name("li5")));
txt_name.sendKeys("Relative locators test");
// Get details of the Submit/Add button
WebElement submitbutton = driver.findElement(By.xpath("//*[@id=\'addbutton\']"));
// Submit the new entry
submitbutton.click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
与Test – 1类似,该项目也必须作为TestNG测试执行。 下面显示的是输出屏幕截图,我们可以在其中看到最后一个选项(即相对定位器测试)已添加到列表中。
我们确信,到现在为止,您已经掌握了Selenium 4相对定位器,可以进行Selenium自动化测试。 由于这是Selenium 4的Alpha版本,因此您可能需要更多时间才能开始为其他编程语言(如Python,C#等)提供对相对定位器的支持。
您对新定位器有何看法?
Selenium 4中的相对定位器是一个有趣的进步,开发人员可以使用它以更少的实现方式访问附近的Web元素。 由于这是Alpha版本,因此功能可能会在其他版本中更改。 重要的是要注意,Selenium 4 Reelative Locator方法(即,上,下,toLeftOf,toRightOf,near)不适用于重叠元素。
如果您将Java与Selenium结合使用来进行自动跨浏览器测试,则一定要试用Selenium 4(Alpha)。 尽管有一些工具(开源和商业工具)提供与Selenium 4 Relative Locator相似的功能,但Selenium 4具有更多功能(包括改进的文档),值得等待!
那么,您如何看待用于硒自动化测试的新定位器? 您是否发现新的Selenium 4相对定位器很方便? 您是否已经计划在自动跨浏览器测试脚本中合并相对定位器? 还是您认为它可以做得更好? 在下面的评论部分中,让我知道您的意见。 测试愉快! 🙂