【问题标题】:Selenium: Opening elements on new window c#Selenium:在新窗口 c# 上打开元素
【发布时间】:2017-07-18 17:09:07
【问题描述】:

我正在使用铬和硒。 我的代码应该打开一个链接,并且在该链接上,它应该打开新页面上的其他可点击项目。为此,我创建了一个动作。当它k==4 时,它会打开一个新窗口,执行某些操作并关闭驱动程序。我写的Action 只能使用一次。 k==5时,使用主驱动,同时关闭主驱动。

for (int k = 4; k < 100; k++) // i do not know how many elements contain
{
    try
    {
        Thread.Sleep(300);
        Actions action = new Actions(secondDriver);
        IWebElement linkInbox = secondDriver.FindElement(By.XPath(element));
        action.KeyDown(Keys.Shift).Click(linkInbox).Perform();
        secondDriver.SwitchTo().Window(secondDriver.WindowHandles.Last());
    }
    catch (Exception)
    {
        Thread.Sleep(500);
    }
    Thread.Sleep(500);
    secondDriver.Close();
    secondDriver.SwitchTo().Window(secondDriver.WindowHandles.First());
}

编辑 1:有没有 Ijavascriptexecutor 解决方案,而不是使用操作?

【问题讨论】:

  • 可以打开新窗口吗?错误是什么?
  • @Buaban 它只适用于 1 一次

标签: c# html selenium selenium-webdriver


【解决方案1】:

我认为您只需要存储CurrentWindowHandle 并在您想要切换回来时使用它。至于Shift+Click,我觉得你最好先用JSExecutor给链接加一个属性target='_blank'再点击。

string mainWindowHandle = secondDriver.CurrentWindowHandle;
for (int k = 4; k < 100; k++) // i do not know how many elements contain
{
  try
  {
    Thread.Sleep(300);
    IWebElement linkInbox = secondDriver.FindElement(By.XPath(element));
    var script = "arguments[0].setAttribute('target','_blank');"
    ((IJavaScriptExecutor)secondDriver).ExecuteScript(script, linkInbox);
    Thread.Sleep(1000);
    linkInbox.Click();
    Thread.Sleep(1000);
    secondDriver.SwitchTo().Window(secondDriver.WindowHandles.Last());
    // do the thing here

    Thread.Sleep(500);
    secondDriver.Close();
    secondDriver.SwitchTo().Window(mainWindowHandle);
  catch (Exception)
  {
    Thread.Sleep(500);
  }
  if(secondDriver.WindowHandles.Count()>1)
  {
    secondDriver.SwitchTo().Window(secondDriver.WindowHandles.Last()).Close();
    secondDriver.SwitchTo().Window(mainWindowHandle);
  }

}

【讨论】:

  • 我试过了。它给出了相同的结果,它只适用于那些。你认为,我也应该持有第二个窗口吗?
  • 我已经更新了答案。我认为尝试有错误,所以它在下一个循环中使用主窗口。
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2011-10-19
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
相关资源
最近更新 更多