GVKun编程网logo

是否等效于使用Java的Selenium WebDriver测试中的waitForVisible / waitForElementPresent?

15

在本文中,我们将给您介绍关于是否等效于使用Java的SeleniumWebDriver测试中的waitForVisible/waitForElementPresent?的详细内容,此外,我们还将为您提

在本文中,我们将给您介绍关于是否等效于使用Java的Selenium WebDriver测试中的waitForVisible / waitForElementPresent?的详细内容,此外,我们还将为您提供关于C# Selenium WebDriverWait 似乎没有等待、c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用、FireFox中的Selenium OpenQA.Selenium.DriverServiceNotFoundException、java – Selenium WebDriver中selenium.waitForPageToLoad(“30000”)的等效代码是什么?的知识。

本文目录一览:

是否等效于使用Java的Selenium WebDriver测试中的waitForVisible / waitForElementPresent?

是否等效于使用Java的Selenium WebDriver测试中的waitForVisible / waitForElementPresent?

通过“ HTML” Selenium测试(通过Selenium
IDE或手动创建),您可以使用一些非常方便的命令,例如 WaitForElementPresent
WaitForVisible

<tr>    <td>waitForElementPresent</td>    <td>id=saveButton</td>    <td></td></tr>

用Java编写Selenium测试(Webdriver / Selenium RC,我不确定这里的术语)时, 是否有类似的内置功能

例如,用于检查对话框(需要一段时间才能打开)是否可见…

WebElement dialog = driver.findElement(By.id("reportDialog"));assertTrue(dialog.isDisplayed());  // often fails as it isn''t visible *yet*

编写此类检查的最干净 可靠的 方法是什么?

Thread.sleep()到处添加呼叫将是丑陋且脆弱的,并且滚动自己的while循环也显得很笨拙…

答案1

小编典典

[隐式和显式等待](http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-

and-implicit-waits)

隐式等待

隐式等待是告诉WebDriver在尝试查找一个或多个元素(如果不是立即可用)时轮询DOM一定时间。默认设置为0。设置后,将在WebDriver对象实例的生存期内设置隐式等待。

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

显式等待+
预期条件

显式等待是您定义的代码,用于等待特定条件发生后再继续执行代码。最糟糕的情况是Thread.sleep(),它将条件设置为要等待的确切时间段。提供了一些方便的方法,可以帮助您编写仅等待所需时间的代码。WebDriverWait与ExpectedCondition结合是实现此目的的一种方法。

WebDriverWait wait = new WebDriverWait(driver, 10);WebElement element = wait.until(        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

C# Selenium WebDriverWait 似乎没有等待

C# Selenium WebDriverWait 似乎没有等待

如何解决C# Selenium WebDriverWait 似乎没有等待?

我正在尝试测试我正在执行搜索的页面。执行搜索后,我首先获取表格元素,获取表格行,然后从行中获取一个或多个以做出我的断言来提取 SearchResults。

我尝试过以多种不同的方式使用 webdriverwaits,但没有成功。我设法从搜索结果中选择项目的唯一可靠方法是使用 Thread.Sleep(3000)。我们正在为我们的表格使用 PrimeNG 库。正在加载的特定表非常大,因此需要等待

硒信息:

  • 硒版本:3.141.0
  • 网络驱动程序类型:ChromeDriver (89.0.4389.2300)
  • Web 驱动程序版本:

浏览器信息:

  • 浏览器类型:Chrome
  • 浏览器版本:90+(在开发机器上)

Web 驱动程序初始化代码: 我通过创建单独的页面对象和页面驱动程序来分离我的页面和自动化代码。这是以 SpecFlow Books example

为模型的

BasePage 类

public class BasePage
{
    protected IWebDriver Driver { get; }
    protected webdriverwait Wait;

    public BasePage(IWebDriver driver)
    {
        Driver = driver;
        Wait = new webdriverwait(Driver,TimeSpan.FromSeconds(10));
    }

    public T As<T>() where T : BasePage
    {
        return (T)this;
    }

    public IWebElement PaginationFirst => Wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.p-paginator-first.p-paginator-element")));
    public IWebElement PaginationLast => Wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.p-paginator-last.p-paginator-element")));
    public IWebElement PaginationPageNumber => Wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.p-paginator-page.p-paginator-element.p-highlight")));

    // Adding waits at this point meant the page elements were timing out due to not being in view.

    public virtual IWebElement ResultTable()
    {
        Thread.Sleep(3000);
        return Driver.FindElement(By.CssSelector("table"));
    }

    public virtual IEnumerable<IWebElement> TableLines()
    {
        return ResultTable().FindElements(By.CssSelector("tableRow"));
    }

    private void WaitUntilElementIsdisplayed(By locator)
    {
        webdriverwait wait = new webdriverwait(Driver,TimeSpan.FromSeconds(5));
        bool Condition(IWebDriver d)
        {
            IWebElement e = d.FindElement(locator);
            Debug.WriteLine(e.displayed);
            return e.displayed;
        }
        wait.Until(Condition);
    }
}

UserListPage 类

public class UserListPage : BasePage
{
    //private readonly webdriverwait _wait;
    //private readonly IWebDriver _driver;
    public UserListPage(IWebDriver driver) : base(driver)
    {
        PageFactory.InitElements(driver,this);
    }

    [FindsBy(How = How.Id,Using = "headingUsers")]
    public IWebElement PageTitle;
    [FindsBy(How = How.Id,Using = "addUser")]
    public IWebElement AddUser;
    public IWebElement TxtSearchEverywhere => Wait.Until(ExpectedConditions.ElementIsVisible(By.Id("txtSearchEverywhere")));
    [FindsBy(How = How.Id,Using = "col-username")]
    public IWebElement ColUsername;
    [FindsBy(How = How.Id,Using = "col-lastname")]
    public IWebElement ColLastname;
    [FindsBy(How = How.Id,Using = "col-firstname")]
    public IWebElement ColFirstname;
    [FindsBy(How = How.Id,Using = "col-hpicpn")]
    public IWebElement ColHpicpn;
    [FindsBy(How = How.Id,Using = "col-facilitycount")]
    public IWebElement ColFacilitycount;
    [FindsBy(How = How.Id,Using = "colRoles")]
    public IWebElement ColRoles;
    [FindsBy(How = How.Id,Using = "col-identitycount")]
    public IWebElement ColIdentitycount;
    [FindsBy(How = How.Id,Using = "colHasLogin")]
    public IWebElement ColHasLogin;
    [FindsBy(How = How.Id,Using = "col-onlinelogin")]
    public IWebElement ColOnlinelogin;
    [FindsBy(How = How.Id,Using = "col-loginstatus")]
    public IWebElement ColLoginstatus;

    public IEnumerable<UserRow> SearchResults => TableLines().Skip(1).Select(r => new UserRow(r));
}

HTML 代码:

<head>
    <body>
        <app-root>
            <header>
                <nav>
                    <main>
                        <app-role><button id="addRole">Add New Role</button>
                            <h2 id="roleTitle">Roles</h2>
                            <peg-admin-list>
                                <p-table currentpagereporttemplate="Showing {first} to {last} of {totalRecords} entries"
                                    ng-reflect-global-filter-fields="roleName,userFriendlyName,user">
                                    <div>
                                        <div>
                                            <div><span><i></i>
                                                <input
                                                        id="txtSearchEverywhere" pinputtext="" type="search" placeholder="Search everywhere"></span><span>
                                                    <p-selectbutton>
                                                        <div role="group">
                                                            <div role="button" aria-pressed="true" title="isActive" aria-label="Active"
                                                                tabindex="0" aria-labelledby="Active">
                                                                <span>Active</span>
                                                            </div>
                                                            <div role="button" aria-pressed="false" title="isActive" aria-label="Inactive"
                                                                tabindex="0" aria-labelledby="Inactive">
                                                                <span>Inactive</span>
                                                            </div>
                                                            <div role="button" aria-pressed="false" title="isSystem" aria-label="Is System"
                                                                tabindex="0" aria-labelledby="Is System">
                                                                <span>Is System</span>
                                                            </div>
                                                        </div>
                                                    </p-selectbutton>
                                                </span>
                                            </div>
                                        </div>
                                        <div>
                                            <table role="grid">
                                                <thead>
                                                    <tr>
                                                        <th>
                                                            Role <p-sorticon ng-reflect-field="roleName"><ing-reflect-ng-></i>
                                                            </p-sorticon>
                                                        </th>
                                                        <th> Reviewer Role Description <p-sorticon ng-reflect-field="userFriendlyName"><ing-reflect-ng-></i>
                                                            </p-sorticon>
                                                        </th>
                                                        <th>
                                                            Users Count <p-sorticon ng-reflect-field="usersCount"><ing-reflect-ng-></i>
                                                            </p-sorticon>
                                                        </th>
                                                        <th> Is
                                                            Active <p-sorticon ng-reflect-field="isActive"><ing-reflect-ng-></i>
                                                            </p-sorticon>
                                                        </th>
                                                        <th> Is System <p-sorticon ng-reflect-field="isSystem"><ing-reflect-ng-></i>
                                                            </p-sorticon>
                                                        </th>
                                                        <th>
                                                            Role Type <p-sorticon ng-reflect-field="roleType"><ing-reflect-ng-></i>
                                                            </p-sorticon>
                                                        </th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td>
                                                            <div>A new Role Test Test with a new name </div>
                                                        </td>
                                                        <td>
                                                            <div>Check if can be seen in Admin2 bob bob bobby bob bob bob </div>
                                                        </td>
                                                        <td>
                                                            <div>4</div>
                                                        </td>
                                                        <td>
                                                            <div> Yes </div>
                                                        </td>
                                                        <tdhttps://www.jb51.cc/tag/stem/" target="_blank">stem">
                                                            <div> No </div>
                                                        </td>
                                                        <td>
                                                            <div> Admin </div>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            <div>A new Test Role</div>
                                                        </td>
                                                        <td>
                                                            <div>Testing changes</div>
                                                        </td>
                                                        <td>
                                                            <div>2</div>
                                                        </td>
                                                        <td>
                                                            <div>Yes</div>
                                                        </td>
                                                        <tdhttps://www.jb51.cc/tag/stem/" target="_blank">stem">
                                                            <div>No</div>
                                                        </td>
                                                        <td>
                                                            <div>Admin</div>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            <div>ADMS</div>
                                                        </td>
                                                        <td>
                                                            <div> </div>
                                                        </td>
                                                        <td>
                                                            <div>2</div>
                                                        </td>
                                                        <td>
                                                            <div>Yes</div>
                                                        </td>
                                                        <tdhttps://www.jb51.cc/tag/stem/" target="_blank">stem">
                                                            <div>No</div>
                                                        </td>
                                                        <td>
                                                            <div>Admin</div>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        <p-paginator>
                                            <span>Showing 1 to 10 of 66
                                                entries</span>
                                            <button type="button" pripple=""https://www.jb51.cc/tag/irs/" target="_blank">irst p-paginator-element p-link p-disabled p-ripple " disabled=""
                                                ng-reflect-ng-><span></span></button>
                                            <button type="button" pripple=""https://www.jb51.cc/tag/dis/" target="_blank">disabled p-ripple" disabled=""
                                                ng-reflect-ng->
                                                <span></span>
                                            </button>
                                            <span>
                                                <button type="button">1</button>
                                                <button type="button">2</button>
                                                <button type="button">3</button>
                                                <button type="button">4</button>
                                                <button type="button">5</button>
                                            </span>
                                            <button type="button">
                                                <span></span>
                                            </button>
                                            <button type="button">
                                                <span></span>
                                            </button>
                                            <p-dropdown style>
                                                <divng-reflect-ng->
                                                    <div><input type="text"></div>
                                                    <span>10</span>
                                                    <div role="button">
                                                        <spanng-reflect-ng-></span>
                                                    </div>
                                                </div>
                                            </p-dropdown>
                                    </div>
                                    </p-paginator>
                                    </div>
                                </p-table>
                            </peg-admin-list>
                        </app-role>
                    </main>
                </nav>
            </header>
        </app-root>
    </body>
</head>

browserDriver 类

public class browserDriver : Idisposable
{
    private readonly browserDriverFactory _browserSeleniumDriverFactory;
    private readonly IConfiguration _config;
    private readonly ConfigurationDriver _configurationDriver;
    private readonly Lazy<IWebDriver> _currentWebDriverLazy;
    private readonly Lazy<webdriverwait> _waitLazy;
    private readonly TimeSpan _waitDuration = TimeSpan.FromSeconds(30);
    private bool _isdisposed;

    public browserDriver(browserDriverFactory browserSeleniumDriverFactory,ConfigurationDriver configurationDriver,IConfiguration config)
    {
        _browserSeleniumDriverFactory = browserSeleniumDriverFactory;
        _config = config;
        _configurationDriver = configurationDriver;
        _currentWebDriverLazy = new Lazy<IWebDriver>(GetWebDriver);
        _waitLazy = new Lazy<webdriverwait>(Getwebdriverwait);
    }

    public IWebDriver Current => _currentWebDriverLazy.Value;

    public webdriverwait Wait => _waitLazy.Value;

    private webdriverwait Getwebdriverwait()
    {
        return new webdriverwait(Current,_waitDuration);
    }

    private IWebDriver GetWebDriver()
    {
        return _browserSeleniumDriverFactory.GetForbrowser(_configurationDriver.Mode);
    }

    public void dispose()
    {
        if (_isdisposed)
        {
            return;
        }

        if (_currentWebDriverLazy.IsValueCreated)
        {
            Current.Quit();
        }

        _isdisposed = true;
    }

    public void Navigate(string urlPart = "")
    {
        if (!Current.Url.EndsWith(urlPart))
        {
            var baseUrl = _config.GetConnectionString("BaseUrl");
            Current.Manage().Window.Maximize();
            Current.Navigate().GoToUrl($"{baseUrl}/{urlPart}");
            RetryHelper.WaitFor(() => Current.Url.EndsWith(urlPart));
        }
    }

}

RoleListPageDriver 类

public class RoleListPageDriver : IRoleListDriver
{
    private readonly browserDriver _browserDriver;
    private readonly IHomeDriver _homeDriver;
    private readonly RoleListPage _roleListPage;
    public IWebElement[] HeaderColumns;

   
    public RoleListPageDriver(browserDriver browserDriver,IHomeDriver homeDriver)
    {
        _browserDriver = browserDriver;
        _homeDriver = homeDriver;
        _roleListPage = new RoleListPage(_browserDriver.Current);
        HeaderColumns = new[]
        {
            _roleListPage.ColRole,_roleListPage.ColDescription,_roleListPage.ColUserCount,_roleListPage.ColIsActive,_roleListPage.ColIsSystem,_roleListPage.ColRoleType
        };
    }

    [AfterScenario()]
    public void dispose()
    {
        _browserDriver.dispose();
    }

    public bool Exists(IWebElement element)
    {
        return element.ElementExists();
    }

    public bool IsLoaded()
    {
        return _roleListPage.PageTitle.ElementExists();
    }

    public void Navigate()
    {
        _browserDriver.Navigate("role");
    }

    public void Search(string searchTerm)
    {
        _roleListPage.TxtSearchEverywhere.Search(searchTerm);
    }

    public void SortColumn(string selector)
    {
        var element = HeaderColumns.Where(h => h.Text == selector).ToList();
        if (element.Count > 0)
        {
            element[0].Clicks();
        }
    }

    public bool TableColumnHeadersExist()
    {
        return HeaderColumns.All(header => header.ElementExists());
    }

    public void RoleMenuExists()
    {
        _roleListPage.ColRole.ElementExists();
    }

    public bool RoleTitleExists()
    {
       return _roleListPage.PageTitle.ElementExists();
    }

    public void RoleListSortResultShouldBeAscendingDescending(string order)
    {
        switch (order)
        {
            case Constants.ListOrder.Ascending:
                _roleListPage.SearchResults.Take(5).Should().BeInAscendingOrder(r => r.RoleName);
                break;
            case Constants.ListOrder.Descending:
                _roleListPage.SearchResults.Take(5).Should().BeInDescendingOrder(r => r.RoleName);
                break;
        }
    }

    public void SearchResultsShouldContainMatchingItems(string searchTerm)
    {
        var searchResult = _roleListPage.SearchResults.Take(1).Select(s => s.RoleName).ToList();
        searchResult.All(str => str.Contains(searchTerm)).Should().BeTrue();
    }

    public void ClickOnFilterButton(string filterButton)
    {
        switch (filterButton)
        {
            case Constants.FilterButton.ActiveRoles:
                _roleListPage.BtnActive.Clicks();
                break;
            case Constants.FilterButton.InactiveRoles:
                _roleListPage.BtnInactive.Clicks();
                break;
            case Constants.FilterButton.IsSystemRoles:
                _roleListPage.BtnIsSystem.Clicks();
                break;
        }
    }

    public void AssertOnlyActiveRolesdisplayed()
    {
        _roleListPage.SearchResults.Take(5).All(r => r.IsActive == "Yes").Should().BeTrue();
    }

    public void AssertOnlyInactiveRolesdisplayed()
    {
        _roleListPage.SearchResults.Take(1).All(r => r.IsActive == "No").Should().BeTrue();
    }

    public void AssertOnlySystemRolesdisplayed()
    {
        _roleListPage.SearchResults.Take(1).All(r => r.IsSystem == "Yes").Should().BeTrue();
    }

    public void ClickOnLastPaginationButton()
    {
        _roleListPage.PaginationLast.Clicks();
    }

    public void AssertLastPageIsdisplayed()
    {
        int.Parse(_roleListPage.PaginationPageNumber.Text).Should().BeGreaterOrEqualTo(3);
    }

    public void AssertPageTitleIsdisplayed(string title)
    {
        _roleListPage.PageTitle.Text.Should().BeEquivalentTo(title);
    }
}

解决方法

BasePage.TableLines() 方法可以使用显式等待:

public virtual IEnumerable<IWebElement> TableLines()
{
   var wait = new WebDriverWait(Driver,TimeSpan.FromSeconds(30));
   var locator = By.CssSelector("table > tbody > tr");

   return wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(locator));
}

这假设在加载数据时表格发生了某种变化。不知道加载结果时表会发生什么,我只能提供这些。

如果在您滚动时动态添加表格行,那最终将是一个完全不同的解决方案。

c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用

c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用

我们有一个.NET 4.5,MVC,C#项目.我们正在使用Selenium进行UI测试,测试会在我们有wait.Until()的行上间歇性地失败.一个这样的例子是:

NoSuchElementException was unhandled by user code
An exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll but was not handled in user code
Additional information: Unable to locate element: {"method":"css selector","selector":"#assessment-472 .status-PushedToSEAS"}

它就在这里抛出:

Thread.Sleep(600);
wait.Until(drv => drv.FindElement(By.CssSelector("#" + assessmentQueueId + " .status-PushedToSEAS")));

我可以看到浏览器打开,我看到它到达那一点,我可以检查元素以查看元素是否存在.它的id完全正确.

我们有这个问题很多,到目前为止解决方案是在它前面抛出Thread.Sleep(600)(或类似的时间). wait.Until()的重点是不必这样做,这使我们的测试套件变得非常长.另外,正如您在上面的示例中所看到的,有时我们甚至在将Thread.Sleep()放在它前面之后也会遇到问题,我们必须延长时间.

为什么.NET Selenium的WebDriver.Until()不起作用,并且有一种不同的方式来做同样的事情而不需要等待一段时间?同样,问题是间歇性的,这意味着它有时只会发生,它可能发生在任何数量的wait.Until()语句中,而不仅仅是显示的那个!

编辑:

这是一个类变量.
私人WebDriver等等;

它实例化如下:

this.wait = new webdriverwait(driver,TimeSpan.FromSeconds(10));

解决方法

我决定不使用webdriverwait.Until(),而是在主驱动程序上使用隐式等待:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

为了给我这个想法,我在一个不同的问题上充分赞扬了this answer.

FireFox中的Selenium OpenQA.Selenium.DriverServiceNotFoundException

FireFox中的Selenium OpenQA.Selenium.DriverServiceNotFoundException

我正在尝试开始编写Selenium测试,并且我编写的第一个非常基本的测试因exception失败OpenQA.Selenium.DriverServiceNotFoundException

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace WebDriverDemo
{
        class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Url = "http://www.google.com";

        }
    }
}

调试器说我需要下载geckodriver.exe并将其设置在我的PATH变量上,这已经完成,但仍然会出现相同的异常。当我对进行相同的操作时ChromeDriver,效果很好。

同样,根据MDN,如果我使用的是Selenium
3.0或更高版本,则应默认启用它。我在Windows 10计算机上使用Selenium 3.0.1。

java – Selenium WebDriver中selenium.waitForPageToLoad(“30000”)的等效代码是什么?

java – Selenium WebDriver中selenium.waitForPageToLoad(“30000”)的等效代码是什么?

以下是在Selenium RC中等待页面加载的 java代码:
selenium.waitForPagetoLoad("30000");

Selenium WebDriver中的等效java代码是什么?

解决方法

2种方法:

>如果你需要等待60秒,你可以使用Thread.sleep(60000)
>如果您想确保页面已加载(可能小于或大于60秒),我建议使用以下方法:

确定目标网页中的元素&等待它可以点击.然后您确定该页面已加载.

webdriverwait wait = new webdriverwait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.id(id)));

WebDriver等待最多120秒.对于可点击的元素.如果元素在此之前可单击,则测试将进行.

今天关于是否等效于使用Java的Selenium WebDriver测试中的waitForVisible / waitForElementPresent?的讲解已经结束,谢谢您的阅读,如果想了解更多关于C# Selenium WebDriverWait 似乎没有等待、c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用、FireFox中的Selenium OpenQA.Selenium.DriverServiceNotFoundException、java – Selenium WebDriver中selenium.waitForPageToLoad(“30000”)的等效代码是什么?的相关知识,请在本站搜索。

本文标签: