Watir-Webdriver:如何获得网站图像的大小(文件大小)

时间:2012-06-26 10:46:09

标签: image watir-webdriver filesize

我有以下HTML代码:                                                 

我看到Watir-webdriver目前不支持“Watir :: Image.file_size”方法。 我发现“Watir-Classic / Image.rb”具有相同的方法,似乎可以使用。

# this method returns the filesize of the image, as an int
def file_size
  assert_exists
  @o.invoke("fileSize").to_i
end

我创建了一个应该检索图像大小的方法,但似乎我没有正确初始化对象。这是我的方法代码:

img_src="/location/on_the_server/image"
chart_image = Watir::Image.new(:src, img_src)
puts chart_image.file_size

问题是我收到以下错误:

"ArgumentError: invalid argument "/location/on_the_server/image""

我看到初始化对象需要(容器,说明符)。我试图将初始化行更改为“chart_image = Watir :: Image.new(img_src,:src)”但错误仍然出现。

有谁能告诉我我做错了什么?

是否有另一种方法可以从网站获取图像的文件大小?

谢谢。

1 个答案:

答案 0 :(得分:2)

您不应该直接初始化Watir :: Image。相反,您应该使用浏览器或元素对象的image()方法。

#Assuming that browser = Watir::Browser that is open
img_src="/location/on_the_server/image"
chart_image = browser.image(:src, img_src)
puts chart_image.file_size

更新 - 下载图片以确定文件大小:

您可以使用open-uri(或类似)下载图像,然后使用Ruby的File类来确定大小:

require 'watir-webdriver'
require "open-uri"

#Specify where to save the image
save_file = 'C:\Users\my_user\Desktop\image.png'

#Get the src of the image you want. In this example getting the first image on Google.
browser = Watir::Browser.new
browser.goto('www.google.ca')
image_location = browser.image.src

#Save the file
File.open(save_file, 'wb') do |fo|
  fo.write open(image_location, :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).read
end

#Output the size
puts File.size(save_file).size
相关问题