【问题标题】:How to add and execute html2canvas on a webpage with Watir如何使用 Watir 在网页上添加和执行 html2canvas
【发布时间】:2018-06-20 21:25:00
【问题描述】:

如何将 html2canvas 添加到给定网页,执行它,然后使用 Watir 读取其结果?

require 'watir'

b = Watir::Browser.new :firefox
b.goto "google.com"

path = "/path/to/html2canvas.js" # v. 0.5.0-alpha1
h2c_payload = File.read(path)
b.execute_script h2c_payload

h2c_activator = %<
  function genScreenshot () {
    var canvasImgContentDecoded;
    html2canvas(document.body, {
      onrendered: function (canvas) {
       window.canvasImgContentDecoded = canvas.toDataURL("image/png");
    }});
  };
  genScreenshot();
>.gsub(/\s+/, ' ').strip
b.execute_script h2c_activator

b.execute_script "return window.canvasImgContentDecoded"
 => nil

在控制台中执行相同的 JavaScript 会导致变量(最终)被设置,然后在调用时返回。 execute_script 有什么不同?

【问题讨论】:

  • 您使用 v0.5.0-alpha1 而不是最新的 v1.0.0-alpha.9 有什么原因吗?
  • @JustinKo 只是因为我找到了该版本的示例,而且似乎没有一个版本是 GM 版本。明天我会尝试更改版本。
  • 最终,1.0 不起作用,但 v0.4.1 可以。感谢您举报!

标签: javascript ruby selenium-webdriver watir


【解决方案1】:

问题是 canvasImgContentDecoded 在画布完成渲染之前被检查。作为一名 JavaScript 程序员,我发现在 Ruby/Watir 中等待更容易:

result = nil
b.wait_until { result = b.execute_script "return window.canvasImgContentDecoded;" }
p result
#=> "data:image/png;base64,iVBORw0KGgoA..."

以上方法只会在使用 Chrome 时解决问题。

Firefox 似乎有其他限制和/或限制阻止原始代码工作。以下在 Firefox 和 Chrome 中有效。请注意,这可能需要更新版本的 html2canvas:

require 'watir'

b = Watir::Browser.new :firefox
b.goto("google.com")

# Load html2canvas - currently  v1.0.0-alpha.9
h2c_payload = %<
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src =  'https://html2canvas.hertzen.com/dist/html2canvas.js';
  document.head.appendChild(script);
>.gsub(/\s+/, ' ').strip
b.execute_script(h2c_payload)

# Wait for html2canvas to load
b.wait_while { b.execute_script("return typeof html2canvas === 'undefined'") }

# Generate the canvas
h2c_activator = 'html2canvas(document.body).then(canvas => {window.canvasImgContentDecoded = canvas.toDataURL("image/png");});'
b.execute_script h2c_activator

# Wait for canvas to be created
result = nil
b.wait_until { result = b.execute_script "return window.canvasImgContentDecoded;" }
p result
#=> "data:image/png;base64,iVBORw0KGgoA..."

【讨论】:

  • 我只收到Watir::Wait::TimeoutError: timed out after 30 seconds, waiting for true condition on #&lt;Watir::Browser:0x..f8ac5dc61862c6c6e url="https://www.google.com/?gws_rd=ssl" title="Google"&gt;。在控制台中,图像会在几秒钟内生成,如果不是更快的话。
  • 哦,有趣。该代码在使用 Chrome 时有效,但不适用于 Firefox。这很麻烦。
猜你喜欢
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
相关资源
最近更新 更多