Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用capybara将图像转换为base64_Ruby On Rails_Ruby_Selenium_Capybara_Poltergeist - Fatal编程技术网

Ruby on rails 使用capybara将图像转换为base64

Ruby on rails 使用capybara将图像转换为base64,ruby-on-rails,ruby,selenium,capybara,poltergeist,Ruby On Rails,Ruby,Selenium,Capybara,Poltergeist,我目前正在使用水豚来运行一些报废任务以及现场测试。我在使用水豚下载图像/文件时遇到困难。我找到的所有文档都是关于简单按钮、表单、链接和交互的指南 如果有人知道如何将网页上的图像下载/转换为base64格式,我将不胜感激。只是浏览了水豚宝石,找到了一个.render\u base64 and save\u屏幕截图方法,可以将图像保存到png或jpg文件中,然后我可以裁剪我想要的部分。方法可在此处找到:此示例使用Capybara/Selenium从网页中提取图像: require 'capybara

我目前正在使用水豚来运行一些报废任务以及现场测试。我在使用水豚下载图像/文件时遇到困难。我找到的所有文档都是关于简单按钮、表单、链接和交互的指南


如果有人知道如何将网页上的图像下载/转换为base64格式,我将不胜感激。

只是浏览了水豚宝石,找到了一个.render\u base64 and save\u屏幕截图方法,可以将图像保存到png或jpg文件中,然后我可以裁剪我想要的部分。方法可在此处找到:

此示例使用Capybara/Selenium从网页中提取图像:

require 'capybara'

JS_GET_IMAGE = "
  var ele = arguments[0], callback = arguments[1], img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function(){
    var cnv = document.createElement('CANVAS');
    cnv.width = this.width;
    cnv.height = this.height;
    cnv.getContext('2d').drawImage(this, 0, 0);
    var type = this.src.endsWith('png') ? 'png' : 'jpeg';
    callback(cnv.toDataURL('image/' + type).substring(22));
  };
  var src = ele.src || window.getComputedStyle(ele).backgroundImage;
  img.src = /https?:/.test(src) ? src.match(/https?:[^\"')]+/)[0] : callback(''); "


session = Capybara::Session.new(:selenium)
driver = session.driver.browser
driver.manage.timeouts.script_timeout = 5000

# navigate to google
session.visit "https://www.google.co.uk/"

# get the logo element
ele = session.find(:css, '#hplogo img:nth-child(1)')

# get the logo as base64 string
imgBase64 = driver.execute_async_script(JS_GET_IMAGE, ele.native)

# save to a file
file = File.new("C:\\temp\\image." + (imgBase64[0] == 'i' ? 'png' : 'jpg'), 'wb')
file.write(Base64.decode64(imgBase64))
file.close

它本机不受支持,但一种方法可能是执行一些js,然后使用base64编码。这里有一个很好的要点,您可以提取重要的部分: