我可以轻松做到
driver.SwitchTo().Window(newTabInstance);
但是我希望能够同时处理多个选项卡,而无需切换到不同的选项卡。基本上,能够同时将javascript插入多个选项卡,而无需在该选项卡上。有没有办法做到这一点?
例如:
tab1.executejavascript("something");
tab2.executejavascript("something");
不可以,如果不切换到不同的选项卡,您将无法同时处理多个选项卡。
<小时 />原因
要执行任何操作,硒都需要专注。除非焦点位于任何特定的 TAB 上,否则 Web 驱动程序将无法在该选项卡/窗口中执行任何操作
编辑:就像@DebanjanB说的,硒需要专注,所以创建一个新类来处理专注并为你重新专注。最终结果正是您所需要的,在多个选项卡中运行脚本,每个选项卡都有一个命令。
public class Tab
{
private readonly string WindowIdentity;
private readonly IWebDriver driver; //If you have a driver static class that can be accessed from anywhere,
// then call the driver directly in the functions below, otherwise, initialize this variable in the constructor.
/// <summary>
/// Default constructor for Tab class, initializes the identity string from driver.
/// </summary>
/// <param name="windowIdentity">The unique string from running driver.</param>
public Tab(string windowIdentity)
{
WindowIdentity = windowIdentity;
}
/// <summary>
/// Runs the given script to the tab.
/// </summary>
/// <param name="script">The script to run.</param>
public void RunScript(string script)
{
//Temporary variable to switch back to.
string initialWindow = driver.CurrentWindowHandle;
driver.SwitchTo().Window(WindowIdentity);
(IJavaScriptExecutor)driver.ExecuteScript(script);
driver.SwitchTo().Window(initialWindow);
}
}
每当有新窗口时,创建一个 Tab 对象以更轻松地管理它
//if the second entry of the array is your new tab
Tab tab1 = new Tab(driver.WindowHandles[1])
然后只需致电
tab1.RunScript("")'
Windows/tabs 有什么区别。只需使用多个窗口,因为 chrome 中的窗口可以加入到其他窗口并充当选项卡。我认为现在应该设计一个解决方法,因为据称硒需要"聚焦"才能"聚焦"在一个选项卡上,因此您无法同时处理不同的选项卡,但您可以打开并行窗口并同时运行它们,从某种意义上说,这些浏览器上的窗口只是它们自己的选项卡,可以加入形成窗口。
如果由于中断其他软件窗口而改变焦点是一个问题,那么使用无头铬是解决方案。因此,所有操作都在后台执行,不会干扰其他窗口。但是,更改选项卡的几毫秒是不可避免的。