簡體   English   中英

使用水豚將圖像轉換為base64

[英]Convert image into base64 using capybara

我目前正在使用水豚來執行一些剪貼任務以及站點測試。 我在使用水豚下載圖像/文件時遇到了困難。 我發現的所有文檔僅指導簡單的按鈕,表單,鏈接交互。

如果有人知道如何將網頁上的圖像下載/轉換為base64格式,將不勝感激。

本示例從帶有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

只是瀏覽了水豚寶石,發現了一個.render_base64和save_screenshot方法,可以將圖像保存到png或jpg文件中,然后我可以裁剪出我想要的部分。 方法可以在這里找到: https : //github.com/teampoltergeist/poltergeist

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM