0
votes

I trying using robot class for saving image...but it not properly working.

    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://agiletesters.com.br");
     Robot rb =new Robot();
     rb.mouseMove(270, 160);
     rb.mousePress(InputEvent.BUTTON3_DOWN_MASK);
     rb.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);

     rb.keyPress(KeyEvent.VK_DOWN);
     Thread.sleep(11000);
     rb.keyRelease(KeyEvent.VK_DOWN);
     rb.keyPress(KeyEvent.VK_ENTER);
     rb.keyRelease(KeyEvent.VK_ENTER);

in this right click is working but it not selecting 'Save image as...' option.

I tried this but download image is not showing:-

try {
         driver = new FirefoxDriver();
         driver.get("http://agiletesters.com.br");
         System.setProperty("http.agent", "Firefox");
         WebElement logo = driver.findElement(By.xpath("//*[@id=\"header-menu\"]/div/div[1]/a/img"));
         String logoSRC = logo.getAttribute("src");

         URL imageURL = new URL(logoSRC);
         BufferedImage saveImage = ImageIO.read(imageURL.openStream());

         ImageIO.write(saveImage, "png", new File("logo-forum.png"));

         } catch (Exception e) {
            e.printStackTrace();
         } finally {
            driver.close();
         }
1

1 Answers

0
votes

My expectation is that your BufferedImage saveImage = ImageIO.read(imageURL.openStream()); is failing due to missing Cookie header

The correct way of downloading file is:

  1. Obtaining current set of cookies from the Firefox browser instance using driver.managet().getCookies() function
  2. Use underlying OKHTTP library to execute the GET request for the logo and save the file.

Example code:

OkHttpClient client = new OkHttpClient().newBuilder().build();

Request request = new Request.Builder().url(logoSRC).addHeader("Cookie", cookies.toString()).build();
Response response = client.newCall(request).execute();

File downloadedLogo = new File("logo-forum.png");
BufferedSink sink = Okio.buffer(Okio.sink(downloadedLogo));
sink.writeAll(Objects.requireNonNull(response.body()).source());
sink.close();