How to Locate Web Elements with Selenium WebDriver?

本文介绍了使用Selenium WebDriver进行UI测试时如何快速准确地定位网页元素。覆盖了各种选择器如ID、CLASS、NAME等,并提供了示例代码。还探讨了如何通过XPath和CSS选择器来定位更复杂的元素。

In order to write UI tests with Selenium WebDriver you need to be able to identify web page elements fast and in an accurate way. You don’t want to revisit these selectors very often so you must choose the right selector from the beginning.

There are some browser tools that you can use in order to identify web elements in the DOM easier. These are:

  • Firebug for Firefox
  • Google Developer Tools for Chrome
  • Web Inspector for Safari

Selenium WebDriver API supports different possibilities to identify elements: by ID, by CLASS, by NAME, by CSS selector, by XPath, by TAG name. Also you define your custom selector in order to interact with the elements.

It’s always a good practice to assign unique IDs to elements, also names and classes in order to be more usable for automatic UI tests. If that is not possible you’ll need to use advanced or XPath selector to interact with those elements. The most popular selectors are the CSS selectors due to performance and simplicity reasons.

To inspect an element you just have to open the desired web page, right-click the desired element and click on Inspect Element. A new panel will open showing the desired element. Also you can inspect other elements by clicking on the cursor in the top left side of the Developer Tools or Firebug panels and hovering page elements.

Locating Elements with Selenium WebDriver, findElement() method returns and WebElement and findElements() returns a list of WebElements.

1. By ID:

1
in Java: driver.findElement(By.id("element id"))

2. By CLASS:

1
in Java: driver.findElement(By.className("element class"))

3. By NAME:

1
in Java: driver.findElement(By.name("element name"))

4. By TAGNAME:

1
in Java: driver.findElement(By.tagName("element html tag name"))

5. By CSS Selector:

1
in Java: driver.findElement(By.cssSelector("css selector"))

6. By Link:

1
in Java: driver.findElement(By.link("link text"))

7. By XPath:

1
in Java: driver.findElement(By.xpath("xpath expression"))

Let’s get a HTML snippet code and see how can we use these Selenium WebDriver selectors in order to identify the desired elements:

1
2
3
4
5
6
7
8
9
10
<div class="thumbnail center well well-small text-center">
<h2>Newsletter</h2>
Subscribe to our weekly Newsletter and stay tuned.
<form action="" method="post" name="subscribe"><label for="name">Name: </label>
 <input class="name" id="name" type="text" placeholder="Enter name..." />
 <label for="email">Email: </label> <input class="email" id="email" type="text" placeholder="your@email.com" />
 <input class="btn btn-large" type="submit" value="Subscribe" /></form>
 <a title="first link" href="#link1">First Link</a>
 <a title="second link" href="#link2">Second Link</a>
</div>

Let’s get some WebElements from the above HTML code snippet:

1
WebElement nameInputField = driver.findElement(By.id("name"));

or

1
WebElement nameInputField = driver.findElement(By.className("name"));

or

1
WebElement emailInputField = driver.findElement(By.id("email"));

Locate link elements with findElements() method from the HTML snipped

1
2
3
4
5
6
7
8
@Test
public void findLinksTest(){
   //Get all the links displayed
   List links = driver.findElements(By.tagName("a"));
   assertEquals(2, links.size());
   for(WebElement link : links)
   System.out.print(link.getAttribute("href"));
}

Locate link elements from the HTML snipped:

How to find a link with Selenium WebDriver API by full text:

1
2
WebElement firstLink = driver.findElement(By.linkText("First Link"));
assertEquals("#link1", firstLink.getAttribute("href"))

How to find a link with Selenium WebDriver API by partial text:

1
2
WebElement firstLink = driver.findElement(By.partialLinkText("First"));
assertEquals("#link1", firstLink.getAttribute("href"))

Locate elements by HTML Tag Name:

1
WebElement subscribeButton = driver.findElement(By.tagName("button"));

Locate elements by CSS Selectors

1
2
WebElement emailInputField =
           driver.findElement(By.cssSelector("form input#email"));

or

1
2
WebElement emailInputField =
           driver.findElement(By.cssSelector("input.email"));

or

1
2
WebElement emailInputField =
           driver.findElement(By.cssSelector("input[type='submit'][value='Subscribe']"));

Performing partial match on attribute values

1
^= as in input[id^='email'] means Starting with.

 

1
$= as in input[id$='_name'] means Ending with.

 

1
*= as in Input[id*='userName'] means Containing.

Finding elements with XPATH

  • Absolute path
1
2
WebElement userName =
           driver.findElement(By.xpath("html/body/div/form/input"));
  • Relative path
1
WebElement email = driver.findElement(By.xpath("//input"));

Finding elements using index

1
2
WebElement email =
           driver.findElement(By.xpath("//input[3]"));

Finding elements using attributes values with XPath

1
2
WebElement logo =
           driver.findElement(By.xpath("img[@alt='logo']"));

XPATH

1
2
3
starts-with()
 
input[starts-with(@id,'input')]

Starting with:

1
2
3
ends-with()
 
input[ends-with(@id,'_field')]

Ending with:

1
2
3
contains()
 
input[contains(@id,'field')]

Containing

Locating table rows and cells

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void testTable() {
   WebElement simpleTable = driver.findElement(By.id("items"));
 
   //Get all rows
   List rows = simpleTable.findElements(By.tagName("tr"));
   assertEquals(3, rows.size());
 
   //Print data from each row
   for (WebElement row : rows) {
      List cols = row.findElements(By.tagName("td"));
      for (WebElement col : cols) {
         System.out.print(col.getText() + "\t");
      }
   System.out.print();
   }
}

Using jQuery selectors

Locate all the Checkbox which are checked by calling jQuery find() method.
find() method returns elements in array

1
2
List elements =
        (List) js.executeScript("return jQuery.find(':checked')");

Refer: https://loadfocus.com/blog/2013/09/how-to-locate-web-elements-with-selenium-webdriver/
基于可靠性评估序贯蒙特卡洛模拟法的配电网可靠性评估研究(Matlab代码实现)内容概要:本文围绕“基于可靠性评估序贯蒙特卡洛模拟法的配电网可靠性评估研究”,介绍了利用Matlab代码实现配电网可靠性的仿真分析方法。重点采用序贯蒙特卡洛模拟法对配电网进行长时间段的状态抽样与统计,通过模拟系统元件的故障与修复过程,评估配电网的关键可靠性指标,如系统停电频率、停电持续时间、负荷点可靠性等。该方法能够有效处理复杂网络结构与设备时序特性,提升评估精度,适用于含分布式电源、电动汽车等新型负荷接入的现代配电网。文中提供了完整的Matlab实现代码与案例分析,便于复现和扩展应用。; 适合人群:具备电力系统基础知识和Matlab编程能力的高校研究生、科研人员及电力行业技术人员,尤其适合从事配电网规划、运行与可靠性分析相关工作的人员; 使用场景及目标:①掌握序贯蒙特卡洛模拟法在电力系统可靠性评估中的基本原理与实现流程;②学习如何通过Matlab构建配电网仿真模型并进行状态转移模拟;③应用于含新能源接入的复杂配电网可靠性定量评估与优化设计; 阅读建议:建议结合文中提供的Matlab代码逐段调试运行,理解状态抽样、故障判断、修复逻辑及指标统计的具体实现方式,同时可扩展至不同网络结构或加入更多不确定性因素进行深化研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值