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]"));
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]"));
IWebElement webElement2 = driver.FindElement(By.XPath($"//a[normalize-space(.)='{myVar}' and @_ngcontent-c32]"));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;
}