2013-10-23 35 views
0

我試圖從一系列通過JS加載的頁面抓取一組信息,並完成了我使用watir-webdriver加載頁面和nokogiri來解析它們。這很好,但是,我需要從頁面中抓取一張照片。圖片的路徑是在頁面加載時生成的,因此我編寫了以下內容來創建一個相對URL的數組,並直接導航到數組第一個索引的絕對URL,這總是我想要的圖像。Ruby Watir-webdriver在直接導航到圖像時保存圖像

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>' 
+0

當使用'File.open'(ie'File.open(「image.jpg」,「wb」)'')時,您可能會想要使用二進制標誌。看到這個例子[SO回答](http://stackoverflow.com/questions/14219768/save-image-in-watir-webdriver) – orde

回答

0

當你這樣做:

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

你是尋找html:

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

我猜你的html不是這樣的,因此你得到了關於在圖像內找到圖像的例外。

你可能只是想解碼類的第一個圖像(刪除圖像配二):

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

或者,也許你需要的圖片的完整列表,然後得到的第一個:

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