0

我试图从通过 JS 加载的一系列页面中获取一组信息,并使用 watir-webdriver 加载页面并使用 nokogiri 解析它们。这很好用,但是,我需要从页面上抓取一张图片。图片的路径是在页面加载时生成的,因此我编写了以下内容来创建图像的相对 URL 数组,并直接导航到数组第一个索引的绝对 URL,这始终是我想要的图像。

img_srcs = $page_html.css('img').map{ |i| i['src'] }    #genereates an array of relative urls pointing to every image
imageURL= "website.com" + img_srcs[1].gsub("..","").to_s    #take the relative URL of image at index position 1 (the image) and converts it to an absolute URL
$browser.goto(imageURL)

如何保存浏览器直接加载的这张图片?任何帮助将不胜感激,如果我有任何不清楚的地方,请告诉我。

编辑:我现在添加了以下代码

image_source = $browser.image(:class => "decoded").image.src
File.open("#{$imageID}.txt", "w") do |f|
    f.write open(image_source).read
    f.close
end

但是,我收到了错误

C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.4/lib/watir-webdriver/el
ements/element.rb:490:in 'assert_exists': unable to locate element, using {:tag_
name=>"img"} (Watir::Exception::UnknownObjectException)
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.4/lib/watir
-webdriver/attribute_helper.rb:71:in 'block in define_string_attribute'
    from 12.rb:121:in 'imageDownload'
    from 12.rb:134:in 'navAndGrab'
    from 12.rb:137:in '<main>'
4

1 回答 1

0

当你这样做时:

$browser.image(:class => "decoded").image.src

您正在寻找 html:

<img class="decoded">
  <img src="what_you_want"></img>
</img>

我猜你的 html 不是那样的,因此你得到关于在图像中查找图像的异常。

您可能只想要第一个带有类解码的图像(删除第二个 .image):

image_source = $browser.image(:class => "decoded").src

或者,也许您想要完整的图像列表,然后获取第一个:

image_source = $browser.images(:class => "decoded").first.src
于 2013-10-23T19:22:34.650 回答