簡體   English   中英

如何在不切換標簽的情況下處理 Selenium 中的多個標簽

[英]How to handle multiple tabs in Selenium without switching tabs

我可以輕松做到

driver.SwitchTo().Window(newTabInstance);

但我希望能夠同時處理多個選項卡而無需切換到不同的選項卡。 基本上,能夠同時將 javascript 插入到多個選項卡中,而無需在該選項卡上。 有沒有辦法做到這一點?

例如:

tab1.executejavascript("something");
tab2.executejavascript("something");

如果不切換到不同的選項卡您將無法同時處理多個選項卡


原因

要執行任何操作Selenium需要focus 除非焦點在任何特定的TAB 的webdriver將無法到該選項卡/窗口中執行任何動作

編輯:就像@DebanjanB 說的,selenium 需要焦點,所以創建一個新類來處理焦點並為你重新焦點。 最終結果正是您所需要的,在多個選項卡中運行腳本,每個選項卡使用一個命令。

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/標簽有什么區別。 只需使用多個窗口,因為Chrome中的Windows可以加入其他窗口並充當標簽。 我認為現在應該設計一種解決方法,因為據稱 selenium 需要“聚焦”才能“聚焦”在一個選項卡上,因此您無法同時處理不同的選項卡,但您可以打開並行窗口並在某種意義上同時運行它們這些瀏覽器上的窗口只是它們自己的選項卡,可以連接起來形成窗口。

如果因為中斷其他軟件窗口而改變焦點是一個問題,那么使用 Headless chrome 是解決方案。 因此,所有操作都在后台執行,不會干擾其他窗口。 但是,更改選項卡的幾毫秒是不可避免的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM