C#Selenium:将变量传递到XPath

时间:2019-02-20 21:07:08

标签: c# selenium variables xpath

我正在尝试将变量传递到XPath中,但是我不知道该怎么做:

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

2 个答案:

答案 0 :(得分:3)

您可以通过将变量嵌入XPath字符串中来实现:

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

答案 1 :(得分:0)

这个问题已经回答了。但是,我建议您可以将此方法添加到脚本中,以在找不到xpath或无效xpath时处理 NoSuchElementException ,也应处理其他Exception。

   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;
    }