我仍然是Selenium测试领域的新手,我目前正在使用Selenium ChromeDriver进行测试。
以下是我试图实现的目标,但没有成功:
1-我在Chrome中打开了大约50个标签,我想一次在所有标签上按下F9
2-按F9键切换到所有选项卡后,如果页面上出现某些文本(无结果),则关闭选项卡。
我希望有人能在这两个特性中的任何一个上提供帮助。
提前谢谢。
发布于 2020-01-15 03:07:55
没有办法(据我所知)一次向多个窗口句柄发送按键(每个选项卡在Selenium中称为一个窗口句柄),但您可以在窗口中循环,并尝试使用某个Actions类将F9按键发送到每个页面,然后检查所需的文本。
您将需要使用Driver.WindowHandles来获取当前打开的选项卡的列表,并使用Driver.SwitchTo().Window()来在选项卡之间切换焦点。Actions类可以模拟将F9密钥发送到当前窗口。Driver.Close()将关闭现有选项卡。
最后,在代码评估当前选项卡是否应该关闭之前,将使用WebDriverWait等待填充“No Results”文本。如果所需的元素在指定的时间参数内没有出现在页面上,WebDriverWait将抛出TimeoutException,因此我们将WebDriverWait包装在try / catch块中,以处理“No Results”既存在又不存在的情况。
下面是C#中的代码示例,您应该可以开始使用了:
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
// given you have 50 tabs open already
// get window handles -- this is a List<string> with length 50, one for each tab
var handles = Driver.WindowHandles;
// iterate window handles, switch to the window, and send F9 key
foreach (var window in handles)
{
    // switch to the window
    Driver.SwitchTo().Window(window);
    // send F9 key press to the current tab
    new Actions(Driver).SendKeys(Keys.F9).Perform();
    // wait for 'No Results' text
    try 
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text(), 'No Results')]")));
        // if TimeoutException is not thrown, then No Results text exists. so close the tab
        Driver.Close();
    }
    catch (TimeoutException)
    {
        // case: 'No Results' text does not exist. do not close the tab.
    }
}这是一个非常笼统的大纲,几乎可以肯定的是,您需要对其进行一些修改才能使其完全正常工作。例如,可能需要调整new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text(), 'No Results')]")));中使用的XPath,以确保定位到显示“No Results”文本的正确元素。希望这篇文章能帮你入门。
https://stackoverflow.com/questions/59739741
复制相似问题