Selenium - дополнительные скриншоты, генерируемые при прокрутке в эквивалентных интервалах для захвата всей веб-страницы. - PullRequest
0 голосов
/ 13 февраля 2019

Цель: Прокрутка в эквивалентных интервалах для создания снимка экрана всей страницы с использованием Java и JSExecutor для Selenium WebDriver.

Проблема: Подход, который я реализовалниже работает, однако , у меня в конечном итоге 2-3 дополнительных снимка экрана в конце веб-страницы - я хочу избежать этих избыточных снимков экрана.

Метод прокрутки ниже:

public static void pageScrollable() throws InterruptedException, IOException {

    JavascriptExecutor jse = (JavascriptExecutor) driver;

    //Find page height
    pageHeight = ((Number) jse.executeScript("return document.body.scrollHeight")).intValue();
    //Find current browser dimensions and isolate its height
    Dimension d = driver.manage().window().getSize();
    int browserSize = d.getHeight();

    int currentHeight = 0;      
    System.out.println("Current scroll at: " + currentHeight);
    System.out.println("Page height is: " + pageHeight + "\n");

    //Scrolling logic
    while(pageHeight>=currentHeight) {  
        jse.executeScript("window.scrollBy(0,"+currentHeight+")", "");
        screenShot();
        currentHeight+=browserSize;
        System.out.println("Current scroll now at: " + currentHeight);
    }   
}

Метод скриншота ниже:

public static void screenShot() throws IOException, InterruptedException {
    File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenShot, new File("C:\\FilePath\\Screen " + count + ".png"));
    count++;
    System.out.println("Current screenshot count: " + count);
}

Следующие переменные определены как статические:

static int pageHeight = 0;
static int count = 0;
static WebDriver driver;

Я понимаю, что в настоящее время нет реализации для захвата экрана всей веб-страницы с помощью Selenium.Любая помощь, чтобы решить мою логику выше, будет принята с благодарностью.

1 Ответ

0 голосов
/ 02 марта 2019

Ваша логика прокрутки является причиной дополнительного изображения.Метод Window.scrollBy прокручивается на количество пикселей, а не на абсолютную позицию.Вам нужно прокрутить по browserSize.

И, возможно, вы должны определить размер окна просмотра вместо размера окна браузера с помощью

int browserSize = ((Number) jse.executeScript("return window.innerHeight")).intValue();

Я добавил полный пример, как получить скриншоты на одной страницес Chrome:

package demo;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.imageio.ImageIO;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverDemo {
  static int pageHeight = 0;
  static int count = 0;
  static WebDriver driver;
  static List<BufferedImage> images = new LinkedList<>();

  public static void main(String[] args) {
    driver = new ChromeDriver();

    driver.get("http://automationpractice.com/");
    try {
      pageScrollable();

    } catch (WebDriverException | InterruptedException | IOException e) {
      e.printStackTrace();
    }

    driver.quit();
  }

  public static void pageScrollable() throws InterruptedException, IOException {

    JavascriptExecutor jse = (JavascriptExecutor) driver;

    // Find page height
    pageHeight = ((Number) jse.executeScript("return document.body.scrollHeight")).intValue();
    // Find current browser dimensions and isolate its height
    int browserSize = ((Number) jse.executeScript("return window.innerHeight")).intValue();
    System.out.println("Page height is: " + pageHeight + "\n");
    System.out.println("Browser height is: " + browserSize + "\n");

    int currentHeight = 0;
    System.out.println("Current scroll at: " + currentHeight);
    System.out.println("Page height is: " + pageHeight + "\n");

    // Scrolling logic
    while (pageHeight >= currentHeight) {
      screenShot();
      currentHeight += browserSize;
      jse.executeScript("window.scrollBy(0," + browserSize + ")", "");
      System.out.println("Current scroll now at: " + currentHeight);
    }

    BufferedImage result = null;
    Graphics2D g2d = null;
    int heightCurr = 0;
    System.out.println("Image count is " + images.size());
    for (int i = 0; i < images.size(); i++) {
      BufferedImage img = images.get(i);
      int imageHeight = 0;
      if (result == null) {
        System.out.println("Image height is " + img.getHeight()); // differs from browserSize
        imageHeight = pageHeight + images.size() * (img.getHeight() - browserSize);
        result = new BufferedImage(img.getWidth(), imageHeight, img.getType());
        g2d = result.createGraphics();
      }
      if (i == images.size() - 1) {
        g2d.drawImage(img, 0, imageHeight - img.getHeight(), null);
      } else {
        g2d.drawImage(img, 0, heightCurr, null);
        heightCurr += img.getHeight();
      }
    }
    g2d.dispose();
    ImageIO.write(result, "png", new File("screenshot.png"));
  }

  public static void screenShot() throws IOException, InterruptedException {
    byte[] scr = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    BufferedImage img = ImageIO.read(new ByteArrayInputStream(scr));
    images.add(img);
  }
}

К сожалению, он не дает правильных результатов с FireFox из-за сбоев в их реализации Window.scrollBy.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...