单击下载按钮在 selenium java 中无法正常工作

clicking the download button is not working properly in selenium java

我没有遇到任何错误,因为没有找到任何元素,但是我的测试用例在控制台中通过了,但是当我检查下载文件夹时,它显示了一些临时文件而不是实际的图像文件。如果有人解决这个问题,将会非常有用。

driver.get("https://demoqa.com/elements");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            
            // Here normal 'findElement' is not working, hence used the javascript executor
            
            WebElement leftmenu = driver.findElement(By.xpath("(//li[@id='item-7']//span)[1]"));
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].click();", leftmenu);  //clicking the left menu 
            
            Thread.sleep(5000);
            
            driver.findElement(By.xpath("//a[@download='sampleFile.jpeg']")).click();  // download button

您正在完成测试 运行 并在单击下载按钮后立即关闭浏览器。
点击后尝试添加简单睡眠
另外,你不应该像这样使用硬编码的暂停

Thread.sleep(5000);

应该改用显式等待。
也请尝试等到元素可见,正如我在这里写的那样。我认为这会让您使用常规驱动程序 .click() 方法单击它。
试试这个:

driver.get("https://demoqa.com/elements");

driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, globalDelay);
            
// Here normal 'findElement' is not working, hence used the javascript executor
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//li[@id='item-7']//span)[1]"))).click();            
//WebElement leftmenu = driver.findElement(By.xpath("(//li[@id='item-7']//span)[1]"));
//JavascriptExecutor executor = (JavascriptExecutor)driver;
//executor.executeScript("arguments[0].click();", leftmenu);  //clicking the left menu 

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@download='sampleFile.jpeg']"))).click();            

Thread.sleep(5000);


on the element Download you can use either of the following

  • linkText:

    driver.findElement(By.linkText("Download")).click();
    
  • cssSelector:

    driver.findElement(By.cssSelector("a#downloadButton[download^='sampleFile']")).click();
    
  • xpath:

    driver.findElement(By.xpath("//a[@id='downloadButton' and starts-with(@download, 'sampleFile')]")).click();
    

理想情况下,click() 在你需要诱导的元素上 for the elementToBeClickable() and you can use either of the following :

  • linkText:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Download"))).click();
    
  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a#downloadButton[download^='sampleFile']"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@id='downloadButton' and starts-with(@download, 'sampleFile')]"))).click();
    

PS: Once you click on Download don't close the web browser immediately and wait for sometime for the download process to be completed.