SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(., 'Medium')' is not a valid XPath expression error using Selenium

SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(., 'Medium')' is not a valid XPath expression error using Selenium

我使用 selenium 尝试在 html 中获取 div class 值,但我遇到了如下问题

invalid selector: Unable to locate an element with the xpath expression //div[contains(., 'Medium') because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(., 'Medium')' is not a valid XPath expression.

下面是我的 html 和读取 html 值的代码。

HTML:

代码试验:

IWebElement element = driver.FindElement(By.XPath("//div[contains(., 'Medium')"));
String text =   element.GetAttribute("text");
Console.WriteLine(text);

这个错误信息...

invalid selector: Unable to locate an element with the xpath expression //div[contains(., 'Medium') because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(., 'Medium')' is not a valid XPath expression.

...表示您使用的 XPath 不是有效的 XPath 表达式。


你们太亲密了。您在构建 .

时错过了结束 ]

实际上你的代码行将是:

IWebElement element = driver.FindElement(By.XPath("//div[contains(., 'Medium')]"));

参考资料

您可以在以下位置找到几个相关的相关讨论:

你的xpath表达式少了关闭]:

IWebElement element = driver.FindElement(By.XPath("//div[contains(., 'Medium')]"));
String text = element.Text;
Console.WriteLine(text);

要提取文本,请使用 element.Text;element.GetAttribute("innerHTML");