我正在尝试使用 selenium 服务器和 python 客户端从网站保存图像。 我知道图像的 URL,但我找不到保存它的代码,无论是文档本身还是嵌入在当前浏览器 session 中。
到目前为止我找到的解决方法是保存页面的屏幕截图(有 2 种 selenium 方法可以做到这一点),但我想要原始图像。
我不介意摆弄点击菜单选项等,但我找不到方法。
谢谢
最佳答案
我找到了将图像放入 Canvas ,然后将其转换为数据的代码——例如,然后可以对其进行 base64 编码。我的想法是在 selenium 中使用 eval 命令来调用它,但是在我的测试中,toDataURL 抛出了安全错误 1000。如果不是因为那个错误,它似乎非常接近解决方案。
var data, canvas, ctx;
var img = new Image();
img = document.getElementById("yourimageID");
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0); // everything works up to here
data = canvas.toDataURL(); // this fails ***
var base64Img = data.replace(/^data:image\/(png|jpg);base64,/, "");
在做一些研究时,我发现当图像来自不同的域时不允许使用 toDataURL。但是,我什至通过保存页面来尝试此代码,剥离除图像本身和此脚本之外的所有内容。
例如(index.html):
<html><head></head><body>
<img src="local/hard/disk/img.jpg" id="yourimageID">
<script>
// script from above
</script>
</body></html>
img.jpg和index.html是保存在本地的,在本地用firefox打开页面,还是安全错误1000!
关于python - 使用 selenium 和 firefox 保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/816704/