Roro Roro - 1 year ago 53
C# Question

C# Selenium Extract Data from span with partial ID

I am trying to create a proper XPATH syntax in C# Selenium to extract an order number on a web page. Here is what I've tried to far to grab the order number shown in the screen shot. All of these have errored out on me.

var result = driver.FindElement(By.XPath("//span[@id^='order-number-'")).Text;
var result = driver.FindElement(By.XPath("//div[@id='a-column a-span7']/h5")).Text;
var result = driver.FindElement(By.XPath("//div[@id='a-column a-span7']/span[@class='a-text-bold']")).Text;

Below is the inspection from Chrome. I am trying to grab the order number, but it will not always be the same so I cannot hard code the span id.

enter image description here

Answer Source

The driver.FindElement(By.XPath("//span[@id^='order-number-'")) would definitely match nothing since ^= is not a valid operator in XPath language. Plus, you are not closing the square brackets.

Instead, if you want to have a shorter and more readable version, use a CSS selector:


Here ^= means "starts with".

If you want to stay with XPath, use starts-with() function:

driver.FindElement(By.XPath("//span[starts-with(@id, 'order-number-')]"))