【问题标题】:how to call element in static void?如何在静态无效中调用元素?
【发布时间】:2019-05-25 01:59:53
【问题描述】:

我正在用 c# 做一个小的 selenium 程序。我想等待最多 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) 需要对象引用

【问题讨论】:

  • 您需要将waitForPageUntilElementIsVisible 方法设为静态。
  • 这次“司机”说不能在静态里面?

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


【解决方案1】:

使方法静态。

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


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

【讨论】:

  • 驱动词这次是红色的,WebDriverWait(错误:非静态字段、方法或属性'Program.driver'需要一个对象引用
  • @UmutPınarbaşı 同样,这次将driver设为静态。阅读静态和非静态成员。
【解决方案2】:

在单独的类中定义此方法,并使用 PageWait 对象调用此方法。

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");

    }
}

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多