简体   繁体   中英

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.

在此处输入图片说明

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:

driver.FindElement(By.CssSelector("span[id^=order-number]"))

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-')]"))

You can try this out:

var result = driver.FindElement(By.XPath("//span[contains(@id, 'order-number-')]")).Text;

It uses a "contains" on the span ID. Let me know if this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM