首页 > 解决方案 > 操作打开新窗口时单击事件超时

问题描述

我正在使用带有 NUnit 和 Chrome 浏览器的 Visual Studio 中的 c# 编写一些硒自动化。在网页中有一个是按钮,它会打开一个新窗口。

该网页指出

你想继续是/否?

回答 [是] 会打开一个新窗口,然后在其中有另一个带有 [打印] 按钮的新窗口

当在 Selenium 中单击 [Yes] 按钮时,新窗口打开但单击事件未完成,代码在单击时挂起,然后在 60 秒后引发超时错误。为了解决这个问题,我将单击包含在 try catch 中以处理错误。然而,下一段代码也会在 60 秒后超时。

完全有机会我让这段代码在调试中的 try-catch 上运行,并发现如果我睡了 9 分钟(总共 10 分钟,包括 60 秒的点击超时),那么代码会继续运行而没有任何进一步的超时。如果我减少睡眠时间,超时失败会再次发生。

try
{
    //This click works but doesnt complete, and then throws a timeout error after 60 seconds and falls into the catch
    DialogYesBtn.Click();

}
catch
{
    Thread.Sleep(540000); //9  minutes if i drop this to 8 minutes then the next step also times out
}

// this works with the above timeouts - if i dont sleep  in the catch this times out after 60 seconds as well 
SeleniumDriver.Instance.SwitchTo().Window(SeleniumDriver.Instance.WindowHandles.Last());

//unable to find this element using POM
PrintBtn.Click(); 

知道这里发生了什么吗?我需要在最后一个窗口中单击一个按钮,但 Selenium 似乎找不到它们。我还需要一个有效的解决方案来解决当前编写的代码,然后等待 10 分钟以等待某种超时发生。

我在 PrintBtn 单击之前放置了以下调试代码部分,以循环浏览每个窗口以查看可用的元素,但在任何窗口中都找不到。

//finds 3 windows, the original and the 2 that opened onclick
List<string> windows = SeleniumDriver.Instance.WindowHandles.ToList();
foreach (var handle in windows)
{

    SeleniumDriver.Instance.SwitchTo().Window(handle);

    //none of these elements are found in any window
    var elems1 = SeleniumDriver.Instance.FindElements(By.Id("header"));
    var elems2 = SeleniumDriver.Instance.FindElements(By.Id("button-strip"));
    var elems3 = SeleniumDriver.Instance.FindElements(By.TagName("control-button"));
    var elems4 = SeleniumDriver.Instance.FindElements(By.ClassName("action-button"));

}

标签: c#seleniumselenium-webdriverwindow-handles

解决方案


进一步调试了 javascript,我认为 Selenium 中没有解决方案。[Yes] 按钮的 javascript onclick 事件创建一个新窗口,其中包含由以下 js 代码创建的 [Print] 按钮:

var printWindow = window.open('', '', 'height=400,width=800');
printWindow.print();

然后它挂在 printWindow.print(); 等待按下打印按钮。在完成之前,[Yes] click 事件不会完成。在使用 Selenium 的“是”按钮的单击事件中,无法在“打印”按钮上执行 Click()。


推荐阅读