简体   繁体   中英

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.

You mixed partial syntax of contains

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

For direct match use =

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

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

  • CssSelector :

     Driver.Instance.FindElement(By.CssSelector("pk-reset>ak-icon.ki-expand")).Click();
  • XPath 1 :

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

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

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