使用Selenium 2将本地图像注入/加载到当前网页中

时间:2011-11-23 14:34:35

标签: java image webdriver selenium-webdriver

我有一个Selenium Java应用程序,它使用JavaScript executor加载自定义JavaScript。以同样的方式,我能够将自定义CSS加载到当前页面。但我也希望能够加载CSS中引用的自定义本地图像。这可能吗?

1 个答案:

答案 0 :(得分:1)

自己动手。参数:

  • styleDefinitions是一个包含css样式表定义的字符串。
  • flatImageFolder是一个布尔值。如果为true,则具有相对URL的所有本地图像都从src/main/resources/images文件夹中获取。如果为false,则必须将它们放在相应子文件夹中的文件夹中。

java代码:

public class SeleniumTools {
    public function loadCSS(String styleDefinitions, Boolean flatImageFolder) {
        Pattern pattern;
        if(flatImageFolder) {
            pattern = Pattern.compile("url\\((?:.*?\\/)(.*?).(png|gif)\\)");
        } else {
            pattern = Pattern.compile("url\\(((?:.*?\\/).*?).(png|gif)\\)");
        }
        Matcher matcher = pattern.matcher(styleDefinitions);
        StringBuffer styleDefinitionsWithInlineImageData = new StringBuffer();
        int lastMatchEndPosition = 0;
        while(matcher.find()) {
            String filename = matcher.group(1);
            String extension = matcher.group(2);
            lastMatchEndPosition = matcher.end();
            matcher.appendReplacement(styleDefinitionsWithInlineImageData, "url(" + convertImageToBinaryData(
                        SeleniumTools.class.getResourceAsStream("/images/" + filename + "." + extension), extension) + ")");
        }
        // add all definitions from the last match until the end of the stylesheet
        styleDefinitionsWithInlineImageData.append(styleDefinitions.substring(lastMatchEndPosition));
        String script = "jQuery('<style type=\"text/css\">" + styleDefinitionsWithInlineImageData.toString() + "</style>').appendTo('html > head');";
        ((JavascriptExecutor) webDriver).executeScript(script);
    }

    private static String convertImageToBinaryData(InputStream imageInputStream, String fileExtension) {
        BufferedImage image;
        try {
            image = ImageIO.read(imageInputStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, fileExtension, baos);
            return "data:image/" + fileExtension + ";base64," + Base64.encode(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}