2012-04-06 116 views
0

我正在編寫一些代碼,它將從文本文件中提取URLS,然後檢查它們是否加載。我的代碼是:循環時出現錯誤

require 'rubygems' 
require 'watir' 
require 'timeout' 

Watir::Browser.default = "firefox" 
browser = Watir::Browser.new 

File.open('pl.txt').each_line do |urls| 
    begin 
    Timeout::timeout(10) do 
     browser.goto(urls.chomp) 
     if browser.text.include? "server" 
     puts 'here the page didnt' 
     else 
     puts 'here site was found' 
     File.open('works.txt', 'a') { |f| f.puts urls } 
     end 
    end 
    rescue Timeout::Error => e 
    puts e 
    end 
end 

browser.close 

的事情是,雖然我得到的錯誤:

execution expired 
/Library/Ruby/Gems/1.8/gems/firewatir-1.9.4/lib/firewatir/jssh_socket.rb:19:in `const_get': wrong number of arguments (2 for 1) (ArgumentError) 
    from /Library/Ruby/Gems/1.8/gems/firewatir-1.9.4/lib/firewatir/jssh_socket.rb:19:in `js_eval' 
    from /Library/Ruby/Gems/1.8/gems/firewatir-1.9.4/lib/firewatir/firefox.rb:303:in `open_window' 
    from /Library/Ruby/Gems/1.8/gems/firewatir-1.9.4/lib/firewatir/firefox.rb:94:in `get_window_number' 
    from /Library/Ruby/Gems/1.8/gems/firewatir-1.9.4/lib/firewatir/firefox.rb:103:in `goto' 
    from samplecodestack.rb:17 
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/timeout.rb:62:in `timeout' 
    from samplecodestack.rb:16 
    from samplecodestack.rb:13:in `each_line' 
    from samplecodestack.rb:13 

有誰知道如何得到它的工作?

+0

如果你想要做的是檢查是否仍然有效的URL,你應該只使用'網:: HTTP'並出具'HEAD'請求。檢查網站正文中的「服務器」一詞將排除許多實際加載不正確的網站。 – 2012-04-06 18:40:58

+0

是的,我嘗試過,但一些網站服務器關閉,腳本最終拋出一個錯誤。 – 2012-04-06 19:13:32

回答

1

您也可以使用net/http並處理超時。

require "net/http" 
require "uri" 
File.open('pl.txt').each_line do |urls| 
    uri = URI.parse(urls.chomp) 
    begin 
     response = Net::HTTP.get_response(uri) 
    rescue Exception=> e 
     puts e.message 
     puts "did not load!" 
    end 
end 

我在跟蹤堆棧跟蹤時遇到了問題,但它似乎在您的goto語句中。

+0

如果你所要做的只是檢查URL的使用net/http或像http-party這樣的gem會更快更簡單,因爲你可以得到HTTP狀態代碼,如果它是2xx或3xx(重定向),那麼它可能是好的,如果它是4xx或5xx,那麼你有某種錯誤。 Watir會更適合實際的功能測試 – 2012-04-07 08:07:03

+0

這是我最後一起去的,謝謝。 – 2012-04-07 17:15:44

0

execution expired是當超出Timeout::timeout的塊時發生的錯誤。請注意,超時正在檢查其整個塊是否在指定時間內完成。鑑於行號錯誤,我猜測被加載的URL花了近10秒,然後文本檢查超時。

我假設你真的只是意味着如果頁面加載時間超過10秒而不是整個測試需要10秒才能完成,那麼超時會發生。所以,你應該移到if語句出超時塊:

File.open('pl.txt').each_line do |urls| 
    begin 
    Timeout::timeout(10) do 
     browser.goto(urls.chomp) 
    end 
    if browser.text.include? "server" 
     puts 'here the page didnt' 
    else 
     puts 'here site was found' 
     File.open('works.txt', 'a') { |f| f.puts urls } 
    end 
    rescue Timeout::Error => e 
    puts 'here the page took too long to load' 
    puts e 
    end 
end 
+0

感謝兄弟,最後我帶着net/http的東西去了,但是你教了我一兩件事,不知道做了整塊的Timeout事情,認爲它只是檢查了網站,就是這樣。 – 2012-04-07 17:16:19