Search code examples
c#seleniumselenium-webdriverxpathxpath-1.0

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


i using selenium try to get the div class value in html, but i hit the problem as per below

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.

Below is my html and my code that read value of html.

HTML:

enter image description here

Code trials:

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

Solution

  • This error message...

    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.
    

    ...implies that the XPath which you have used was not a valid XPath expression.


    You were so close. You missed the closing ] while constructing the .

    Effectively your line of code will be:

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

    References

    You can find a couple of related relevant discussions in: