如何在 WebDriver 中保存本地缓存中的图像?

How to save images from local cache in WebDriver?

我通过

通过 WebDriver (Chrome) 从网页下载图像
// STEP 1
$driver->get($link);

// STEP 2
$els=$driver->findElements(WebDriver\WebDriverBy::tagName('img'));

foreach ($els as $el) {
$src=$el->getAttribute('src');
$image=file_get_contents($src);
file_put_contents("image.jpg",$image);
}

图片已经被浏览器载入,我需要在第2步重新下载图片

我可以通过 right-click 在浏览器中保存步骤 1 之后的图像,并且 Save image as ... 无需互联网连接,因为图像在浏览器的本地缓存中可用。

是否可以将Chrome加载的图片用WebDriver保存下来而不用重新下载?

上面的代码是PHP,但是随便命中或者其他编程语言的示例代码都可以解决问题。

下面的 java 代码会将图像(或任何文件)下载到您想要的目录中。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class imageDownload{

       public static void main(String[] args) throws IOException {
              URL img_url = new URL("image URL here");
              String fileName = img_url.getFile();
              String destName = "C:/DOWNLOAD/DIRECTORY" + fileName.substring(fileName.lastIndexOf("/"));

              InputStream is = img_url.openStream();
              OutputStream os = new FileOutputStream(destName);

              byte[] b = new byte[2048];
              int length;

              while ((length = is.read(b)) != -1) {
                     os.write(b, 0, length);
              }

              is.close();
              os.close();
       }
}

首先,您的图像的所有字节流都将存储在对象 'is' 中,并且该字节流将被重定向到 OutputStream 对象 os 以创建一个文件(一种复制-粘贴,但作为 0 和 1)。