简体   繁体   English

如何通过Selenium C#使用文本查找元素

[英]How to find an element using text through Selenium C#

I have the following html:我有以下 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.当我尝试使用 text() 时,我收到一条错误消息,指出它不是有效的 XPath 表达式。 Everywhere I look on the internet uses that syntax.我在互联网上看到的任何地方都使用这种语法。 I'm very new to c#/Selenium/XPath values.我对 c#/Selenium/XPath 值很陌生。 Any help is very much appreciated.很感谢任何形式的帮助。

You mixed partial syntax of contains你混合了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 : CSS选择器

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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