1
我有一個Selenium Java應用程序,該應用程序使用JavaScript executor加載自定義JavaScript。以同樣的方式,我可以加載自定義CSS到當前頁面。但我也希望能夠加載在CSS中引用的自定義本地圖像。那可能嗎?使用Selenium 2將本地圖像加載到當前網頁中
我有一個Selenium Java應用程序,該應用程序使用JavaScript executor加載自定義JavaScript。以同樣的方式,我可以加載自定義CSS到當前頁面。但我也希望能夠加載在CSS中引用的自定義本地圖像。那可能嗎?使用Selenium 2將本地圖像加載到當前網頁中
明白了。參數:
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;
}
}
你的意思是像''?瀏覽器應該在處理CSS時自動執行此操作。 –
我無法使用URL,因爲沒有運行Web服務器。我必須以某種方式序列化圖像或使用二進制格式將它們直接包含在源代碼中。 – Alp