How to get the correct XPath for a column title using C# and selenium webdriver?

Viewed 27

I have the following HTML

<label class="ms-Label headerText-269" title="Reference Id">Reference Id</label>

which I am trying to locate using XPath. I have written the following which doesn't seem to work.

driver.FindElement(By.XPath("//title[contains(text(),'Reference Id']"));

Any help would be appreciated.

Thanks

4 Answers

Try the below

driver.FindElement(By.XPath("//label[contains(text(),'Reference Id']"));

OR

 driver.FindElement(By.XPath("//*[normalize-space()='Reference Id']"));

In this element the tag name is label while title is attribute name as well as class is attribute name.
XPath expression is normally has the following structure

//tagname[@attributeName='attributeValue']

or

//tagname[contains(@attributeName,'attributeValue')]

etc.
So, you can try the following command:

driver.FindElement(By.XPath("//label[contains(text(),'Reference Id')]"));

Or

driver.FindElement(By.XPath("//label[contains(.,'Reference Id')]"));

There are many ways you could identify the xpath based attributes.

If you want identify by its text then

//label[text()='Reference Id']

By title attribute

//label[@title='Reference Id']

So your c# code should be like

driver.FindElement(By.XPath("//label[text()='Reference Id']"));

Or

 driver.FindElement(By.XPath("//label[@title='Reference Id']"));

You can refer following reference to understand more about xpath xpath

Here the tagname is label, also we can directly use the text() instead of contains() if the text Reference id is static. The xpath would be:

driver.FindElement(By.XPath("//label[text()='Reference Id']"));

Related