The difference between find_element and find_elements
Overview
There are two similar method in Selenium.
For Python or Ruby
- find_element
- find_elements
For Java or C#
- findElement/FindElement
- findElements/FindElements
[A.find_element / findElement]returns a web element.
[B.find_elements / findElements]returns the list of elements.
All tag have a unique id and a common class.
Usage
Code example for getting elements with XPath.
Python
driver.find_element_by_xpath('XPath')
driver.find_elements_by_xpath('XPath') #Enclose string with " or '
Java
driver.findElement(By.xpath('XPath'));
driver.findElements(By.xpath('XPath')); //Enclose string with "
C#
driver.FindElement(By.XPath("XPath")); //XPath
driver.FindElements(By.XPath("XPath")); //Enclose string with "
Ruby
driver.find_element(:xpath, 'XPath')
driver.find_elements(:xpath, 'XPath') #Enclose string with " or '
JavaScript
driver.findElement(By.xpath('XPath'));
driver.findElements(By.xpath('XPath')); //Enclose string with " or '
Python
Sample code
The program to get and click the element In Selenium.
# -*- coding:utf-8 -*- from selenium import webdriver driver_path = r'D:\Selenium\driver\chromedriver.exe' driver = webdriver.Chrome(executable_path=driver_path) driver.get("https://selenium-world.net/page/test_link1.html"); #find_element element = driver.find_element_by_xpath('//a[@class="link"]') #find_elements elements = driver.find_elements_by_xpath('//a[@class="link"]') elements[0].click() driver.quit()
In a development editor, you will need to restart the script every time you enter code. You’ll need to launch a new Selenium and to display the target page.
CodeChecker allows you to run code as many times as you like while keeping the target screen open in your browser.
Case1(find_element)
[A.find_element] Specify the class.
When you enter the code in the code field and press the “Code" button, you can get elements.
Input code
driver.find_element_by_xpath('//a[@class="link"]')
Return value
<selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="8ca5f5d4-5e0a-4567-b769-9f90f6b5a902")>
There are five elements that matched to the specified class, but the return value is one WebElement.
Selenium returns the first matching element.
Case2(find_elements)
[B.find_elements] Specify the class.
Input code
driver.find_elements_by_xpath('//a[@class="link"]')
Return value
[<selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="8ca5f5d4-5e0a-4567-b769-9f90f6b5a902")>, <selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="b763fa4c-621a-4989-b4cb-fa099d55bf3a")>, <selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="a3bfa971-be58-4105-8bd0-2f5cb2e61a71")>, <selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="97bed18b-aa45-4b7a-8bbb-526a0b246a3e")>, <selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="b97ad028-8fee-40fb-a2ee-669763f7cca0")>]
All the matching elements are returned as a list (array), such as [element1, element2, element3…].
Type
Input code
type(driver.find_elements_by_xpath('//a[@class="link"]')) #get type
Output
<class 'list'> #list object
List elements
To operate the elements, you need to get the element from the returned list.
Input code
driver.find_elements_by_xpath('//a[@class="link"]')[0]
Return value
<selenium.webdriver.remote.webelement.WebElement (session="4eabe4f404fb3885f85c1142eb8bd621", element="8ca5f5d4-5e0a-4567-b769-9f90f6b5a902")>
Selenium returns the WebElement.
Case3(find_elements:No element)
[B.find_elements] If you specify a wrong class, Selenium will not get the elements.
Input code
driver.find_elements_by_xpath('//a[@class="xxxx"]')
Retrun value
[]
Selenium will return an empty list.
Get the list element
When you get an element from the empty list, an exception will occur.
Inupt code
driver.find_elements_by_xpath('//a[@class="xxxx"]')[0]
Output
IndexErrorlist index out of range<traceback object at 0x000001EB8EAF21C8>
That is a Python exception, not a Selenium exception.
Case4(find_element:No element)
[A.find_element] If you specify a wrong class, an exception occurs.
Input code
driver.find_element_by_xpath('//a[@class="xxxx"]')
Output
NoSuchElementExceptionMessage: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class="xxxx"]"}
(Session info: chrome=83.0.4103.116)
<traceback object at 0x000001EB8EAF2348>
That is a Selenium exception.
Case5(To operate)
find_element
[A.find_element] Operate the returned WebElement.
Input code
driver.find_element_by_xpath('//a[@id="link1"]').click()
find_elements
[B.find_elements] Get an element from the returned list.
Input code
driver.find_elements_by_xpath('//a[@id="link1"]')[0].click()
Exception of find_elements
[B.find_elements] The returned list has no click method.
Input code
driver.find_elements_by_xpath('//a[@id="link1"]').click()
Output
AttributeError'list' object has no attribute 'click'<traceback object at 0x000001EB8EAF2F88>
An exception occurs.
existence check of the element
[B.find_elements] If Selenium does not get the element, no exception will be thrown. Therefore, it is used to check the existence of the element.
Input code
list1 = driver.find_elements_by_xpath('//a[@class="xxxx"]')
print(len(list1))
if len(list1) == 0:
print("No Element")
Output
0
No Element
Loop
[B.find_elements] It stores the elements in a list (array). So it is used in a loop processing.
Sample1
Input code
list1 = driver.find_elements_by_xpath('//a[@class="link"]')
for element in list1:
print(element.text)
Output
Link1
Link2
Link3
Link4
Link5
Sample2
Input code
list1 = driver.find_elements_by_xpath('//a[@class="link"]')
i=0
while i < len(list1):
print(list1[i].text)
i += 1
Output
Link1
Link2
Link3
Link4
Link5
Java
Sample code
package example.test; import java.util.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class App { public static void main( String[] args ) { System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://selenium-world.net/page/test_link1.html"); //findElement WebElement element = driver.findElement(By.xpath("//a[@class='link']")); //findElements ArrayList<WebElement> elements = new ArrayList<WebElement> (driver.findElements(By.xpath("//a[@class='link']"))); elements.get(0).click(); driver.quit(); } }
Rewrite the code if necessary and check the operation.
Case1(findElement)
[A.findElement] Specify the class.
Input code
System.out.println(driver.findElement(By.xpath("//a[@class='link']")));
System.out.println(driver.findElement(By.xpath("//a[@class='link']")).getClass().getName());
Output
[[ChromeDriver: chrome on WINDOWS (63c99009f44b79608809e2577a90fe8c)] -> xpath: //a[@class='link']]
org.openqa.selenium.remote.RemoteWebElement
There are five elements that matched to the specified class, but the return value is one RemoteWebElement.
Selenium returns the first matching element.
Case2(findElements)
[B.findElements] Specify the class.
Input code
System.out.println(driver.findElements(By.xpath("//a[@class='link']")));
System.out.println(driver.findElements(By.xpath("//a[@class='link']")).getClass().getName());
Output
[[[ChromeDriver: chrome on WINDOWS (63c99009f44b79608809e2577a90fe8c)] -> xpath: //a[@class='link']], [[ChromeDriver: chrome on WINDOWS (63c99009f44b79608809e2577a90fe8c)] -> xpath: //a[@class='link']], [[ChromeDriver: chrome on WINDOWS (63c99009f44b79608809e2577a90fe8c)] -> xpath: //a[@class='link']], [[ChromeDriver: chrome on WINDOWS (63c99009f44b79608809e2577a90fe8c)] -> xpath: //a[@class='link']], [[ChromeDriver: chrome on WINDOWS (63c99009f44b79608809e2577a90fe8c)] -> xpath: //a[@class='link']]]
java.util.ArrayList
All the matching elements are returned as a ArrayList.
ArrayList elements
To operate the elements, you need to get the element from the returned ArrayList.
Input code
System.out.println(driver.findElements(By.xpath("//a[@class='link']")).get(0));
System.out.println(driver.findElements(By.xpath("//a[@class='link']")).get(0).getClass().getName());
Output
[[ChromeDriver: chrome on WINDOWS (38543984b6bf0654417de6d77dfa0a3e)] -> xpath: //a[@class='link']]
org.openqa.selenium.remote.RemoteWebElement
Selenium returns the RemoteWebElement.
Case3(findElements:No element)
[B.findElements] If you specify a wrong class, Selenium will not get the elements.
Input code
System.out.println(driver.findElements(By.xpath("//a[@class='xxxx']")));
System.out.println(driver.findElements(By.xpath("//a[@class='xxxx']")).getClass().getName());
Output
[]
java.util.ArrayList
Selenium will return an empty ArrayList.
Get the ArrayList element
When you get an element from the empty ArrayList, an exception will occur.
Input code
driver.findElements(By.xpath("//a[@class='xxxx']")).get(0);
Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
That is a Java exception, not a Selenium exception.
Case4(findElement:No element)
[A.findElement] If you specify a wrong class, an exception occurs.
Input code
driver.findElement(By.xpath("//a[@class='xxxx']"));
Output
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='xxxx']"}
(Session info: chrome=84.0.4147.89)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
That is a Selenium exception.
Case5(To operate)
findElement
[A.findElement]Operate the returned WebElement.
Input code
WebElement element = driver.findElement(By.xpath("//a[@class='link']"));
element.click();
findElements
[B.findElements] Get an element from the returned ArrayList.
Input code
driver.findElements(By.xpath("//a[@class='link']")).get(0).click();
Exception of find_elements
[B.findElements] The returned list has no click method.
Input code
driver.findElements(By.xpath("//a[@class='link']")).click();
The above code does not compile.
existence check of the element
[B.findElements] If Selenium does not get the element, no exception will be thrown. Therefore, it is used to check the existence of the element.
Input code
ArrayList<WebElement> elements = new ArrayList<WebElement>
(driver.findElements(By.xpath("//a[@class='xxxx']")));
if (elements.size() == 0){
System.out.println("No Element");
}
Output
No Element
Loop
[B.findElements] It stores the elements in a list (array). So it is used in a loop processing.
Sample1
Input code
ArrayList<WebElement> elements = new ArrayList<WebElement>
(driver.findElements(By.xpath("//a[@class='link']")));
for(WebElement element:elements){
System.out.println(element.getText());
}
Output
Link1
Link2
Link3
Link4
Link5
Sample2
Input code
ArrayList<WebElement> elements = new ArrayList<WebElement>
(driver.findElements(By.xpath("//a[@class='link']")));
int i=0;
while(i < elements.size()){
System.out.println(elements.get(i).getText());
i++;
}
Output
Link1
Link2
Link3
Link4
Link5
C#
Sample code
using System; using System.Collections.ObjectModel; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace SampleTest { class Program { static void Main(string[] args) { String path = @"D:\Selenium\driver"; //C#はフォルダを指定 IWebDriver driver = new ChromeDriver(path); driver.Navigate().GoToUrl ("https://selenium-world.net/page/test_link1.html"); //FindElement IWebElement element = driver.FindElement(By.XPath("//a[@class='link']")); //FindElements ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//a[@class='link']")); elements[0].Click(); driver.Quit(); } } }
Rewrite the code if necessary and check the operation.
Case1(FindElement)
[A.FindElement] Specify the class.
Input code
Console.WriteLine(driver.FindElement(By.XPath("//a[@class='link']")));
Console.WriteLine(driver.FindElement(By.XPath("//a[@class='link']")).GetType());
Output
Element (id = 912f4746-132d-492c-9b9d-848538848478)
OpenQA.Selenium.Remote.RemoteWebElement
There are five elements that matched to the specified class, but the return value is one RemoteWebElement.
Selenium returns the first matching element.
Case2(FindElements)
[B.FindElements] Specify the class.
Input code
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='link']")));
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='link']")).GetType());
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//a[@class='link']"));
foreach(IWebElement element in elements)
{
Console.WriteLine(element);
}
Output
System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]
System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]
Element (id = 3af8afc8-4292-45b2-bff5-bb4dec3f2dd0)
Element (id = e65f605b-70e8-4a2a-8da4-a662b232c7dc)
Element (id = e6f1c212-ffab-4356-ad8a-2d51f6ed7ebf)
Element (id = a04a78cf-9dd5-4aab-bbbd-398e92b5e64d)
Element (id = 8a539cea-6c9f-4f3b-8443-ab06ecaad4d5)
All the matching elements are returned as a Collection.
Collection elements
To operate the elements, you need to get the element from the returned Collection.
Input code
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='link']"))[0]);
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='link']"))[0].GetType());
Output
Element (id = 27ba3021-0752-4ccd-b0b8-019ffbf914b9)
OpenQA.Selenium.Remote.RemoteWebElement
Selenium returns the RemoteWebElement.
Case4(FindElements:No element)
[B.FindElements] If you specify a wrong class, Selenium will not get the elements.
Input code
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='xxxx']")).GetType());
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='xxxx']")).Count());
Output
System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]
0
Selenium will return an empty Collection.
Get the Collection element
When you get an element from the empty Collection, an exception will occur.
Input code
Console.WriteLine(driver.FindElements(By.XPath("//a[@class='xxxx']"))[0]);
Output
Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
That is a C# exception, not a Selenium exception.
Case4(FindElement:No element)
[A.FindElement] If you specify a wrong class, an exception occurs.
Input code
driver.FindElement(By.XPath("//a[@class='xxxx']"));
Output
Exception thrown: 'OpenQA.Selenium.NoSuchElementException' in WebDriver.dll
An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll
Additional information: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='xxxx']"}
(Session info: chrome=84.0.4147.105)
That is a Selenium exception.
Case5(To operate)
FindElement
[A.FindElement] Operate the returned WebElement.
Input code
IWebElement element = driver.FindElement(By.XPath("//a[@class='link']"));
element.Click();
FindElements
[B.FindElements] Get an element from the returned Collection.
Input code
driver.FindElements(By.XPath("//a[@class='link']"))[0].Click();
Exception of find_elements
[B.FindElements] The returned collection has no click method.
Input code
driver.FindElements(By.xpath("//a[@class='link']")).click();
The above code does not compile.
existence check of the element
[B.FindElements]
If Selenium does not get the element, no exception will be thrown. Therefore, it is used to check the existence of the element.
Input code
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//a[@class='xxxx']"));
if (elements.Count() == 0)
{
Console.WriteLine("No Element");
}
Output
No Element
Loop
[B.FindElements] It stores the elements in a collection. So it is used in a loop processing.
Sample1
Input code
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//a[@class='link']"));
foreach (IWebElement element in elements)
{
Console.WriteLine(element.Text);
}
Output
Link1
Link2
Link3
Link4
Link5
Sample2
Input code
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//a[@class='link']"));
int i = 0;
while (i < elements.Count())
{
Console.WriteLine(elements[i].Text);
i++;
}
Output
Link1
Link2
Link3
Link4
Link5
Ruby
Sample code
require "selenium-webdriver" Selenium::WebDriver::Chrome.driver_path = 'D:\Selenium\driver\chromedriver.exe' driver = Selenium::WebDriver.for :chrome driver.get("https://selenium-world.net/page/test_link1.html") #find_element element = driver.find_element(:xpath, '//a[@class="link"]') #find_elements elements = driver.find_elements(:xpath, '//a[@class="link"]') elements[0].click driver.quit
Rewrite the code if necessary and check the operation.
Case1(find_element)
[A.find_element] Specify the class.
Input code
puts driver.find_element(:xpath, '//a[@class="link"]')
puts driver.find_element(:xpath, '//a[@class="link"]').class
Output
#<Selenium::WebDriver::Element:0x0000000007064288>
Selenium::WebDriver::Element
There are five elements that matched to the specified class, but the return value is one Element.
Selenium returns the first matching element.
Case2(find_elements)
[B.find_elements]Specify the class.
Input code
puts driver.find_elements(:xpath, '//a[@class="link"]')
puts driver.find_elements(:xpath, '//a[@class="link"]').class
puts driver.find_elements(:xpath, '//a[@class="link"]').size
puts driver.find_elements(:xpath, '//a[@class="link"]').length
Output
#<Selenium::WebDriver::Element:0x000000000706eeb8>
#<Selenium::WebDriver::Element:0x000000000706ee40>
#<Selenium::WebDriver::Element:0x000000000706edc8>
#<Selenium::WebDriver::Element:0x000000000706ed50>
#<Selenium::WebDriver::Element:0x000000000706ecd8>
Array
5
5
All the matching elements are returned as a Array object.
Array elements
To operate the elements, you need to get the element from the returned Array.
Input code
puts driver.find_elements(:xpath, '//a[@class="link"]')[0]
puts driver.find_elements(:xpath, '//a[@class="link"]')[0].class
Output
#<Selenium::WebDriver::Element:0x00000000070b7898>
Selenium::WebDriver::Element
Selenium returns the Element.
Case3(find_elements:No element)
[B.find_elements] If you specify a wrong class, Selenium will not get the elements.
Input code
puts driver.find_elements(:xpath, '//a[@class="xxxx"]').class
puts driver.find_elements(:xpath, '//a[@class="xxxx"]')
puts driver.find_elements(:xpath, '//a[@class="xxxx"]').size
Output
Array
0
Selenium will return an empty Array.
Get the element
When you get an element from the empty Array as NilClass, an exception will occur.
Input code
puts driver.find_elements(:xpath, '//a[@class="xxxx"]')[0].class
puts driver.find_elements(:xpath, '//a[@class="xxxx"]')[0]
begin
puts driver.find_elements(:xpath, '//a[@class="xxxx"]')[0].click
rescue => error
puts error
puts error.class
end
Output
NilClass
undefined method `click' for nil:NilClass
NoMethodError
That is a Ruby exception, not a Selenium exception.
Case4(find_element:No element)
[A.find_element] If you specify a wrong class, an exception occurs.
Input code
begin
driver.find_element(:xpath, '//a[@class="xxxx"]').click
rescue => error
puts error
puts error.class
end
Output
no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class="xxxx"]"}
(Session info: chrome=84.0.4147.89)
Selenium::WebDriver::Error::NoSuchElementError
That is a Selenium exception.
Case5(To operate)
find_element
[A.find_element]Operate the returned WebElement.
Input code
element = driver.find_element(:xpath, '//a[@class="link"]')
element.click
find_elements
[B.find_elements]Get an element from the returned “Array".
Input code
driver.find_elements(:xpath, '//a[@class="link"]')[0].click
Exception of find_elements
[B.find_elements] The returned Array has no click method.
Input code
begin
driver.find_elements(:xpath, '//a[@class="link"]').click
rescue => error
puts error
puts error.class
end
Output
undefined method `click' for #<Array:0x0000000007197600>
NoMethodError
An exception occurs.
existence check of the element
[B.find_elements] If Selenium does not get the element, no exception will be thrown. Therefore, it is used to check the existence of the element.
Input code
elements = driver.find_elements(:xpath, '//a[@class="xxxx"]')
if elements.size == 0 then
puts "No Element"
end
Output
No Element
Loop
[B.find_elements]
It stores the elements in an array. So it is used in a loop processing.
Sample1
Input code
driver.find_elements(:xpath, '//a[@class="link"]').each{|element|
puts element.text
}
Output
Link1
Link2
Link3
Link4
Link5
Sample2
Input code
elements = driver.find_elements(:xpath, '//a[@class="link"]')
i=0
while i < elements.size do
puts elements[i].text
i += 1
end
Output
Link1
Link2
Link3
Link4
Link5
JavaScript
Sample code
let webdriver = require('selenium-webdriver'); let chrome = require('selenium-webdriver/chrome'); let By = webdriver.By; (async () => { var driver = await new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .setChromeService(new chrome.ServiceBuilder( "D:\\Selenium\\driver\\chromedriver.exe") ) .build(); await driver.get("https://selenium-world.net/page/test_link1.html"); //findElement var element = await driver.findElement(By.xpath("//a[@class='link']")); //findElements var elements = await driver.findElements(By.xpath("//a[@class='link']")); await elements[0].click(); await driver.quit(); })();
Node.js processes asynchronously. “async/await" controls the processing order.
Case1(findElement)
[A.findElement] Specify the class.
Input code
console.log(await driver.findElement(By.xpath("//a[@class='link']")));
Output
WebElement {driver_: Driver, id_: Promise}
There are five elements that matched to the specified class, but the return value is one WebElement.
Selenium returns the first matching element.
Case2(findElements)
[B.findElements] Specify the class.
Input code
var elements = await driver.findElements(By.xpath("//a[@class='link']"));
console.log(elements)
console.log(elements.constructor);
Output
(5) [WebElement, WebElement, WebElement, WebElement, WebElement]
ƒ Array()
All the matching elements are returned as “Array".
await
Write “await" before “driver", not before “console.log".
Input code
console.log(await driver.findElement(By.xpath("//a[@class='link']")));
console.log(await driver.findElements(By.xpath("//a[@class='link']")));
await console.log(driver.findElement(By.xpath("//a[@class='link']")));
await console.log(driver.findElements(By.xpath("//a[@class='link']")));
Output
WebElement {driver_: Driver, id_: Promise}
(5) [WebElement, WebElement, WebElement, WebElement, WebElement]
WebElementPromise {driver_: Driver, id_: Promise, then: ƒ, catch: ƒ, getId: ƒ}
Promise {<pending>}
Array elements
[B.findElements]To operate the elements, you need to get the element from the returned Array.
Input code
var elements = await driver.findElements(By.xpath("//a[@class='link']"));
console.log(elements[0]);
Output
WebElement {driver_: Driver, id_: Promise}
Selenium returns the WebElement.
Promise
You cannot get elements with the following code.
Input code
console.log(await driver.findElements(By.xpath("//a[@class='link']")));
console.log(await driver.findElements(By.xpath("//a[@class='link']"))[0]);
Output
(5) [WebElement, WebElement, WebElement, WebElement, WebElement]
undefined
When you get it in one line, you need to use the “then" method.
Input code
console.log(await driver.findElements(By.xpath("//a[@class='link']")).then(elements => elements[0]));
Output
WebElement {driver_: Driver, id_: Promise}
Case3(findElements:No element)
[B.findElements] If you specify a wrong class, Selenium will not get the elements.
Input code
console.log(await driver.findElements(By.xpath("//a[@class='xxxx']")));
Output
(0) []
Selenium will return an empty array.
Get the array element
When you get an element from the empty Array as “undefined", an exception will occur.
Input code
var elements = await driver.findElements(By.xpath("//a[@class='xxxx']"));
try{
console.log(elements[0]);
await elements[0].click();
}catch(e) {
console.log(e.name);
console.log(e.message);
}
Output
undefined
TypeError
Cannot read property 'click' of undefined
That is a JavaScript exception, not a Selenium exception.
Case4(findElement:No elememnt)
[A.findElement] If you specify a wrong class, an exception occurs.
Input code
try{
await driver.findElement(By.xpath("//a[@class='xxxx']"));
}catch(e) {
console.log(e.name);
console.log(e.message);
}
Output
NoSuchElementError
find_element/index.js:34
no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='xxxx']"}
(Session info: chrome=84.0.4147.89)
That is a Selenium exception.
Case5(To operate)
findElement
[A.findElement] Operate the returned WebElement.
Input code
await driver.findElements(By.xpath("//a[@class='link']")).click();
findElements
[B.findElements] Get an element from the returned “Array".
Input code
var elements = await driver.findElements(By.xpath("//a[@class='link']"));
await elements[0].click();
//In the case using then method
await driver.findElements(By.xpath("//a[@class='link']")).then(elements => elements[0].click());
Exception of find_elements
[B.findElements] The returned Array has no click method
Input code
var elements = await driver.findElements(By.xpath("//a[@class='link']"));
try{
await elements.click();
}catch(e) {
console.log(e.name);
console.log(e.message);
}
Output
TypeError
elements.click is not a function
An exception occurs.
existence check of the element
[B.findElements] If Selenium does not get the element, no exception will be thrown. Therefore, it is used to check the existence of the element.
Input code
var elements = await driver.findElements(By.xpath("//a[@class='xxxx']"));
if (elements.length == 0){
console.log("No Element");
}
Output
No Element
Loop
[B.findElements] It stores the elements in a list (array). So it is used in a loop processing.
Sample1
Input code
let map = webdriver.promise.map;
var elements = await driver.findElements(By.xpath("//a[@class='link']"));
var vals = await map(elements, element => element.getText()).then();
vals.forEach(val => console.log(val));
Output
Link1
Link2
Link3
Link4
Link5
Sample2
Input code
let map = webdriver.promise.map;
var elements = await driver.findElements(By.xpath("//a[@class='link']"));
var vals = await map(elements, element => element.getText()).then();
i=0
while(i < vals.length){
console.log(vals[i]);
i++;
}
Output
Link1
Link2
Link3
Link4
Link5
Summary
Pyhon
A.find_element
Get the element | driver.find_element_by_xpath(“XPath") |
Return type | WebElement |
No element | Ex:NoSuchElementException |
Multiple elements | Selenium return the first matching element. |
B.find_elements
Get the element | driver.find_elements_by_xpath(“XPath")[0] |
Return type | list |
No element | [](empty list) |
Count elements | len(driver.find_elements_by_xpath(“XPath")) |
Get element from the empty list | Ex:IndexErrorlist index out of range |
Click the list object | Ex:AttributeError’list’ object has no attribute 'click’ |
Java
A.findElement
Get the element | driver.findElement(By.xpath(“XPath")); |
Return type | RemoteWebElement |
No element | Ex:NoSuchElementException |
Multiple elements | Selenium return the first matching element. |
B.findElements
Get the element | driver.findElements(By.xpath(“XPath")).get(0); |
Return type | ArrayList |
No element | [](empty ArrayList) |
Count elements | driver.findElements(By.xpath(“XPath")).size(); |
Get element from the empty ArrayList | Ex:IndexOutOfBoundsException |
Click the ArrayList object | Compilation error |
C#
A.FindElement
Get the element | driver.FindElement(By.XPath(“XPath")); |
Return type | IWebElement |
No element | Ex:NoSuchElementException |
Multiple elements | Selenium return the first matching element. |
B.FindElements
Get the element | driver.FindElements(By.XPath(“XPath"))[0] |
Return type | Collection |
No element | Empty collection |
Count elements | driver.FindElements(By.XPath(“XPath")).Count() |
Get element from the empty collection | Ex:System.ArgumentOutOfRangeException |
Click the collection | Compilation error |
Ruby
A.find_element
Get the element | driver.find_element(:xpath, 'XPath’) |
Return type | Selenium::WebDriver::Element |
No element | NoSuchElementError |
Multiple elements | Selenium return the first matching element. |
B.find_elements
Get the element | driver.find_elements(:xpath, 'XPath’)[0] |
Return type | Array |
No element | Empty Array |
Count elements | driver.find_elements(:xpath, 'XPath’).size |
driver.find_elements(:xpath, 'XPath’).length | |
Get element from the empty Array | NilClass |
Click the Array object | Ex:NoMethodError:undefined method `click’ for #<Array> |
JavaScript
A.findElement
Get the element | await driver.findElement(By.xpath(“//a[@class=’link’]")); |
Return type | WebElement |
No element | Ex:NoSuchElementError |
Multiple elements | Selenium return the first matching element. |
B.findElements
Get the element |
await driver.findElements (By.xpath(“//a[@class=’link’]")) .then(elements => elements[0].click()); |
var elements = await driver.findElements(By.xpath(“//a[@class=’link’]")); await elements[0].click(); |
|
Return type | Array |
No element | Empty Array |
Count elements |
await driver.findElements (By.xpath(“//a[@class=’link’]")) .then(elements => elements.length) |
var elements = await driver.findElements(By.xpath(“//a[@class=’link’]")); elements.length;
|
|
Get element from the empty Array | undefined |
Click the Array object | Ex:TypeError |
Discussion
New Comments
No comments yet. Be the first one!