christopherhe1
christopherhe1

Reputation: 39

How to find an element using text through Selenium C#

I have the following html:

<p class="k-reset"><a class="k-icon k-i-expand" href="#" tabindex="-1"></a>Unit: QA Room: 1</p>

I can't seem to get valid syntax to click on this element. I've tried the following:

IWebElement webElement5 = Driver.Instance.FindElement(By.XPath("//a[@class='k-icon k-i-expand']"));
webElement5.Click();
IWebElement webElement5 = Driver.Instance.FindElement(By.XPath("//p[text(), 'Unit: QA Room: 1']"));
webElement5.Click();

When I try to use the text(), I get an error stating that it is not a valid XPath expression. Everywhere I look on the internet uses that syntax. I'm very new to c#/Selenium/XPath values. Any help is very much appreciated.

Upvotes: 0

Views: 1638

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

To click on the element you can use either of the following solution:

  • CssSelector:

    Driver.Instance.FindElement(By.CssSelector("p.k-reset>a.k-icon.k-i-expand")).Click();
    
  • XPath 1:

    Driver.Instance.FindElement(By.XPath("//p[@class='k-reset']/a[@class='k-icon k-i-expand']")).Click();
    
  • XPath 2:

    Driver.Instance.FindElement(By.XPath("//p[@class='k-reset' and normalize-space()='Unit: QA Room: 1']")).Click();
    

Upvotes: 0

Guy
Guy

Reputation: 50809

You mixed partial syntax of contains

"//p[contains(text(), 'Unit: QA Room: 1')]"

For direct match use =

"//p[text()='Unit: QA Room: 1']"

Upvotes: 2

Related Questions