0

How to pass a variable string within the xpath to identify an element in Selenium and Java?

Code trials:

System.out.println("Name:\n");
String name = sc.nextLine();
System.out.println("Enter the no. of messages:\n");
int count = sc.nextInt();
System.out.println("Enter what you want to send:\n");
String mess = sc.next(); 
System.out.println("Enter anything after you have scanned the QR");
String a = sc.next();

driver.findElement(By.xpath("//span[@title='Rinmay AEI']")).click();

I want my user input name String to be placed instead of 'Rinmay AEI'

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

1 Answers1

0

Instead of hardcoding the value of title attribute, make it a variable and and you can use either of the following Locator Strategies:

  • cssSelector:

    System.out.println("Name:\n");
    String name = sc.nextLine();
    // other lines of code
    driver.findElement(By.cssSelector("span[title='" + name + "']")).click();
    
  • xpath:

    System.out.println("Name:\n");
    String name = sc.nextLine();
    // other lines of code
    driver.findElement(By.xpath("//span[@title='" + name + "']")).click();
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352