0

我有以下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)”,但错误不断出现。

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

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

谢谢你。

4

1 回答 1

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
于 2012-06-26T13:13:11.137 回答