如何在静态void中调用元素?

时间:2019-05-25 01:59:53

标签: c# selenium selenium-webdriver selenium-chromedriver

我正在用c#做一些硒程序。我想等待最多5秒钟来互动按钮或其他可见的按钮。我已经为此编写了一个代码,但是我不能在static void main内调用该代码,它说一个对象是必需的非静态字段。我该如何解决 ? 错误:非静态字段,方法或属性'Program.waitForPageUntilElementIsVisible(By,int)

需要对象引用

班计划     {         IWebDriver公共驱动程序;

    static void Main(string[] args)
    {
        IWebDriver driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://www.mail.com/int/");
        IWebElement login = driver.FindElement(By.Id("login-button"));
        login.Click();
        IWebElement email = driver.FindElement(By.Id("login-email"));
        waitForPageUntilElementIsVisible(By.Id("login-email"), 5);
        email.SendKeys("CarlosdanielGrossen95@mail.com");


    }


        public  IWebElement waitForPageUntilElementIsVisible(By locator,int maxseconds)
    {


       return new  WebDriverWait(driver, TimeSpan.FromSeconds(maxseconds))
            .Until(ExpectedConditions.ElementExists((locator)));
    }

}
}

非静态字段,方法或属性'Program.waitForPageUntilElementIsVisible(By,int)

需要对象引用

2 个答案:

答案 0 :(得分:1)

使方法静态。

        public static IWebElement waitForPageUntilElementIsVisible(By locator,int maxseconds)
    {


       return new  WebDriverWait(driver, TimeSpan.FromSeconds(maxseconds))
            .Until(ExpectedConditions.ElementExists((locator)));
    }

答案 1 :(得分:0)

在一个单独的类中定义此方法,然后使用PageWait Object调用此方法。

public class PageWait
{
  public  IWebElement waitForPageUntilElementIsVisible(By locator,int maxseconds)
    {
       return new  WebDriverWait(driver, TimeSpan.FromSeconds(maxseconds))
            .Until(ExpectedConditions.ElementExists((locator)));
    }
}

class Program { 
public IWebDriver driver;

    static void Main(string[] args)
    {
        IWebDriver driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://www.mail.com/int/");
        IWebElement login = driver.FindElement(By.Id("login-button"));
        login.Click();
        IWebElement email = driver.FindElement(By.Id("login-email"));
        new PageWait().waitForPageUntilElementIsVisible(By.Id("login-email"), 5);
        email.SendKeys("CarlosdanielGrossen95@mail.com");

    }
}