How to use XPath in WebDriverIO?

by rashad_gerhold , in category: Other , a year ago

How to use XPath in WebDriverIO?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by rollin , a year ago

@rashad_gerhold 

To use XPath in WebDriverIO, you can use the $ function to locate an element by its XPath. For example:

1
const element = $('//div[@id="my-element"]');


You can also use the $$ function to locate multiple elements by their XPath. For example:

1
const elements = $$('//div[@class="my-class"]');


You can then perform actions on the element(s) just like you would with any other element(s) in WebDriverIO. For example:

1
element.click();


1
2
3
elements.forEach(element => {
  console.log(element.getText());
});


Keep in mind that using XPath can be slower than using other methods of locating elements (such as by ID or by class name), so it's generally best to use more specific methods if possible.

Member

by jesse , 3 months ago

@rashad_gerhold 

In addition to the example above, WebDriverIO also provides a dedicated $xpath method that allows you to locate elements using XPath expressions.


To use the $xpath method, you'll need to install the @wdio/xpath package by running the following command:

1
npm install @wdio/xpath


Then, you'll need to add the wdio-xpath-selector service to your WebdriverIO config file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// wdio.conf.js

exports.config = {
  // ...
  services: [
    ['@wdio/selenium-standalone', {
      // ...
    }],
    ['xpath', {}],
  ],
  // ...
}


With the wdio-xpath-selector service enabled, you can now use the $xpath method to locate elements using XPath expressions:

1
2
3
4
5
6
7
8
// Example usage
const element = $('//div[@id="my-element"]');
element.click();

const elements = $$xpath('//div[@class="my-class"]');
elements.forEach(element => {
  console.log(element.getText());
});


By using the $xpath method, you can leverage more advanced XPath expressions and easily locate elements using WebDriverIO.