[英]Convert image into base64 using capybara
I'm currently using capybara to run some scrapping tasks as well as site testing. 我目前正在使用水豚来执行一些剪贴任务以及站点测试。 I have been having difficulties in downloading images/files using capybara.
我在使用水豚下载图像/文件时遇到了困难。 All the documentations I found only guides on simple buttons,forms, links interaction.
我发现的所有文档仅指导简单的按钮,表单,链接交互。
Would really appreciate it if someone knows how to download/convert images on a webpage into base64 format. 如果有人知道如何将网页上的图像下载/转换为base64格式,将不胜感激。
This example extracts an image from a web page with Capybara / Selenium : 本示例从带有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
Just looked through the capybara gem and found a .render_base64 and save_screenshot method which could save the image into png or jpg file and after that i could crop the part i wanted. 只是浏览了水豚宝石,发现了一个.render_base64和save_screenshot方法,可以将图像保存到png或jpg文件中,然后我可以裁剪出我想要的部分。 Method can be found here: https://github.com/teampoltergeist/poltergeist
方法可以在这里找到: https : //github.com/teampoltergeist/poltergeist
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.