如何用Chrome Webdriver关闭下载横幅?

在我的测试中,我下载了一个文件,它工作正常,但后来当我试图点击一个元素我无法滚动到视图时,页面底部的chrome下载对话框就挡了。 没有办法移动我需要点击进入视图的按钮,那么有没有办法用chrome webdriver关闭该下载框?

您可以使用org.openqa.selenium.interactions.Actions类移动到元素view

 WebElement element = driver.findElement(By.id("my-id")); Actions actions = new Actions(driver); actions.moveToElement(element); // actions.click(); actions.perform(); 

回答你的问题:

,目前无法通过Selenium / WebDriver访问(并因此关闭)浏览器的下载对话框(在您的案例中为chrome)。

你可以做什么:

  • 使用浏览器开发人员工具(按F12)确定您要单击的按钮是否具有ID或其他以找到它
  • 然后你可以做driver.findElement(yourLocator).click();

让我们说你的按钮是这样的:

然后,您可以按如下方式定义定位器:

By yourLocator = By.id("my-button");

您可以使用下面的代码段打开下载网页,然后将其关闭并返回目标网页:

 action.sendKeys(Keys.CONTROL+ "j").build().perform(); action.keyUp(Keys.CONTROL).build().perform(); Thread.sleep(500); ArrayList tabs2 = new ArrayList (driverChrome.getWindowHandles()); driverChrome.switchTo().window(tabs2.get(1)); Thread.sleep(500); driverChrome.close(); driverChrome.switchTo().window(tabs2.get(0)); Thread.sleep(500); 

发送控制键不适合我,但我开发了一种解决方法。 我在新窗口中进行任何下载测试,然后关闭下载窗口,原始窗口没有下载栏。 它必须是一个新窗口,如果你做一个新标签,它将转移,为此我使用JavaScript。 切换到新窗口,运行下载测试,完成后切换到原始窗口。

 string javascript = $"$(window.open('', '_blank', 'location=yes'))"; ((IJavaScriptExecutor)Driver).ExecuteScript(javascript); //create new window Driver.SwitchTo().Window(Driver.WindowHandles.Last())); //switch to new window //do download test here Driver.Close(); //close created window Driver.SwitchTo().Window(Driver.WindowHandles.First()); //back to original window with no download bar