How to identify the elements by partially comparing to its attributes in Selenium?


We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.

Syntax 

driver.findElement(By.xpath("//tagname[contains(@attributes,’value’)]"))

In CSS, we can identify elements by partially comparing to its attributes by using regular expressions. There can be three scenarios −

  • Using ^ to target attributes starting with a particular text.

    Syntax

    driver.findElement(By.cssSelector("tagname[attribute^=’value’]"))
  • Using $ to target attributes ending with a particular text.

    Syntax 

    driver.findElement(By.cssSelector("tagname[attribute$=’value’]"))
  • Using * to target attributes containing a particular text.

    Syntax 

    driver.findElement(By.cssSelector("tagname[attribute*=’value’]"))

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PartialMatch {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // xpath with contains() method driver.findElement(By.xpath("input[contains(@id,’gsc-i’)]"))
      .click();
      // css with class name attribute starting with gsc
      driver.findElement(By.cssSelector("input[class^=’gsc’)]"))
      .click();
      // css with class attribute ending with button v2
      driver.findElement(By.cssSelector("button[class$=’button-v2’)]")).
      click();
      // css with id attribute containing Selenium
      driver.findElement(By.cssSelector("input[id*=’gsc-i’)]"))
      .click();
      driver.close();
   }
}

Updated on: 10-Jun-2020

979 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements