2013-05-13 38 views
0

假設,以下是HTML代碼:如何確保使用Selenium webdriver不會破壞鏈接?

<a href="http://www.google.com">Google</a> 

通過下面的代碼,我可以確保href是用於鏈接:

expected_href = "http://www.google.com" 
actual_href = driver.find_element(:tag_name, "a").attribute("href") 

unless actual_href == expected_href 
    puts "Link is incorrect" 
end 

但我要確保鏈接「http://www.google.com 「沒有損壞意味着如果我向」http://www.google.com「發出請求,它的迴應應該是狀態」200「

我該如何測試?有沒有Ruby庫來測試http請求?

+0

'broken'意味着什麼?需要更多相同的信息。 – 2013-05-13 13:07:15

+0

我想在不打開該鏈接的情況下測試此功能(意味着避免點擊鏈接)。使用一些Ruby庫向該網址發送請求,並將它的響應和檢查響應的狀態設置爲200 – TDHM 2013-05-13 13:16:47

回答

0

這裏是URI doc

require 'uri' 

expected_href = "http://www.google.com" 
actual_href = "http://google.com" 
uri1 = URI(actual_href) 
uri2 = URI(expected_href) 
puts "Link is incorrect" unless [uri1.host,uri1.scheme] == [uri2.host,uri2.scheme] 
#=> Link is incorrect 

或者你可以看看這裏的其他方式Net HTTP get source code and status

+0

您的上述代碼不會向網址發送請求,因此無法獲取它的狀態。但是你指出的鏈接非常有幫助。使用這些鏈接,我可以解決問題。感謝您的幫助! – TDHM 2013-05-13 14:09:52

+0

Humm有多種方法可以解決您所遇到的問題,並且我會盡可能讓您知道。這就是它:) – 2013-05-13 14:11:38

0

下面的代碼對我的作品:

require 'open-uri' 
require 'selenium-webdriver' 

expected_status = ["200", "OK"] 

link = driver.find_element(:tag_name, "a").attribute("href") 
io = open(link) 
link_status = io.status 

unless expected_status == link_status 
    puts "Link is broken" 
end 
+0

這不是在這個社區好。你只是複製了我給你的答案。可能你可以把它作爲**編輯**放到你的文章中。 – 2013-05-13 14:13:11

+0

問題是如何使用selenium-webdriver檢查返回狀態?使用'open-uri'給出解決方案並不能回答這個問題。 – jmervine 2013-06-07 04:47:05