1

I am trying to pass a variable into my XPath, but I can't figure out how to do this:

string myVar = "Activities";
IWebElement webElement2 = driver.FindElement(By.XPath("//a[normalize-space(.)='Activities' and @_ngcontent-c32]"));

2 Answers 2

4

You can achieve this by embedding the variable into the XPath string:

IWebElement webElement2 = driver.FindElement(By.XPath("//a[normalize-space(.)='" + myVar + "' and @_ngcontent-c32]"));
Sign up to request clarification or add additional context in comments.

1 Comment

Or on newer C# versions: IWebElement webElement2 = driver.FindElement(By.XPath($"//a[normalize-space(.)='{myVar}' and @_ngcontent-c32]"));
0

This question is already answered . However, i recommended that you may add this method to your script to handle NoSuchElementException when your xpath is not found or invalid and also handle other Exceptions as well .

   public static bool existsElement(IWebDriver _driver,By by,int waitBySecond,string message)
    {
        WebDriverWait wait = new WebDriverWait(_driver, new TimeSpan(0, 0, waitBySecond));

        wait.Message = message;

        try
        {
            // check _driver.FindElement(by) or wait element to check

        }
        catch (WebDriverTimeoutException ex)
        {
            Console.WriteLine("Message : " + ex.Message);
            Console.WriteLine("StackTrace: " + ex.StackTrace);

            return false;
        }

        catch(NoSuchElementException ex)
         {
           Console.WriteLine("Message : " + ex.Message);
           Console.WriteLine("StackTrace: " + ex.StackTrace);
          return false;
         }
        catch(Exception e)
        {
            Console.WriteLine("Message : " + wait.Message);
            Console.WriteLine("StackTrace: " + ex.StackTrace);

            return false;
        }



        return true;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.