使用Webdriver使用Selenium进行超时的最佳方法是什么 [英] What is the best approach for Timeout using Selenium using Webdriver

查看:83
本文介绍了使用Webdriver使用Selenium进行超时的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题.我的网页有一个DropDownList控件. DropDownList值更改后(通过选择其他值),页面将刷新并呈现内容.

I have run into a problem. My web page has a DropDownList control. Once the DropDownList value changes (by selecting a different value), the page refreshes and it renders the contents.

然后我必须先使用Thread.Sleep(2000);FindElement.

我的问题:等待网页加载的最佳方法是什么?

My question: What is the best way to wait till the page loads?

我的代码中有很多Thread.Sleep(2000)实例,我开始认为这不是解决问题的最佳方法.

I have so many instances of Thread.Sleep(2000) in my code that I am beginning to think this is not the best way to approach the problem.

这是我的代码:

[TestInitialize()]
public void Setup()
{
    if (BaseIntegrationTest.browserType.Equals(BaseIntegrationTest.IE))
    {
        driver = new InternetExplorerDriver();
    }
    else if (BaseIntegrationTest.browserType.Equals(BaseIntegrationTest.CHROME))
    {
        //driver = new ChromeDriver();
    }
    else if (BaseIntegrationTest.browserType.Equals(BaseIntegrationTest.FIREFOX))
    {
        driver = new FirefoxDriver();
    }
}

第二部分:

[TestMethod]
public void testVerifyData()
{
    // ...................
    // ...................
    driver.FindElement(By.XPath("//*[@id='ctl00_NavigationControl1_lnke']")).Click();

    Thread.Sleep(2000);

    //select from the dropdownlist.
    IWebElement catagory = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Filter"));
    SelectElement selectCatagory = new SelectElement(catagory);
    selectCatagory.SelectByText("Employee");

    Thread.Sleep(2000);
    // ...................
    // ...................
}

推荐答案

Thread.Sleep()是一种非常不鼓励执行等待的方法

Thread.Sleep() is a very discouraged way to implement your waits

硒代码 http://seleniumhq.org/docs/04_webdriver_advanced.html

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement category = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(By.Id("ctl00_ContentPlaceHolder1_Filter"));
    });

这是一个显式等待的示例,其中硒在找到您的元素之前不会执行任何操作

That is an example of an explicit wait where selenium will not execute any actions until your element is found

隐式等待的示例是:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
IWebElement category = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Filter"));

在隐式等待中,驱动程序将等待给定的时间,并在DOM中轮询不存在的任何元素.

In implicit waits the driver will wait for a given amount of time and poll the DOM for any elements that do not exist.

编辑

public WaitForElement(string el_id)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    IWebElement category = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(By.Id(el_id));
    });
}

这篇关于使用Webdriver使用Selenium进行超时的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆