How to append a new string within an Xpath

615 views
Skip to first unread message

Radhika Joshi

unread,
Mar 24, 2020, 4:01:59 AM3/24/20
to seleniu...@googlegroups.com
Hi all,

I have script where I get a PIN (a numerical string) and based on it I append F, L and  E characters to the xpath of various elements.
for instance, the PIN I received is : 2919398
I stored it in a String pin= " 2919398 ";
Now the xpaths that i have is :    
   WebElement FirstName = driver.findElement(By.xpath("//*[@id='F2919398']"));
   WebElement LastName = driver.findElement(By.xpath("//*[@id='L2919398']"));
   WebElement Email = driver.findElement(By.xpath("//*[@id='E2919398']"));

Is there any way that i can insert this pin in xpath id in the form of a string variable without having to create 3 new variables for the same??

Thanks & Regards,
Radhika Joshi

John Underatker

unread,
Mar 24, 2020, 4:15:10 AM3/24/20
to seleniu...@googlegroups.com
Hi,

Declare a sting say 
private static final String abc = "%s123456";
And then you can use:
findElement(By.xpath(String.format(abc, <here put the dynamic thing f, e, l you want>)))

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to selenium-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/selenium-users/CALLrrpLQ%3DUfdY3J3iqsYp6eY0yBfz-Fqn5VcLfAEz6vfNQT5vg%40mail.gmail.com.

John Underatker

unread,
Mar 24, 2020, 4:16:17 AM3/24/20
to seleniu...@googlegroups.com
Make sure the String mentioned had complete xpath with just the dynamic string you want as %

Radhika Joshi

unread,
Mar 24, 2020, 4:34:39 AM3/24/20
to seleniu...@googlegroups.com

user...@comcast.net

unread,
Mar 24, 2020, 4:43:25 AM3/24/20
to seleniu...@googlegroups.com

It is not completely clear what you are trying to do. It looks like you want to dynamically create an xpath address using the pin. Not sure what language you are using, but in python you could use the replace command to get what you want. A simple example is posted below. I used XX to indicate the spot where I want to replace characters in the predefined string mask. Note that you can replace those characters with more new characters than were in the mask (for instance you can insert 7 new characters where only two were before). Hope this helps:

 

first_name_mask =("//*[@id='FXX']")

pin = '2919398'

first_name = first_name_mask.replace("XX",pin)

print(first_name)

--

Reply all
Reply to author
Forward
0 new messages