简体   繁体   中英

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.

This example extracts an image from a web page with 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. Method can be found here: https://github.com/teampoltergeist/poltergeist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM