2012-07-02 76 views
1

我正在開發一個應用程序在rails中需要檢查輸入網站的網址是否存在或不存在?例如,如果用戶輸入http://google.com,那麼它應該返回「Sitemaps present」。我已經看到了解決方案,通常網站在URL的末尾有/sitemap.xml或/ sitemap。所以我試着用typhoeus gem,檢查URL的response.code(如www.google.com/sitemap.xml或www.apple.com/sitemap),如果它返回的是200或301,則存在站點地圖,否則不會。但是我發現即使他們沒有網站地圖,一些網站會返回301,但他們會將其重定向到他們的主頁(例如http://yournextleap.com/sitemap.xml),因此我沒有得到確鑿的結果。任何幫助都會非常棒。 這裏是我的示例代碼來檢查網站地圖使用百頭巨怪:感動永久用於 永久重定向Ruby代碼來檢查網站是否有網站地圖

# the request object 
request = Typhoeus::Request.new("http://apple.com/sitemap") 

# Run the request via Hydra. 
hydra = Typhoeus::Hydra.new 

request.on_complete do |response| 
    if response.code == 301 
    p "success 301" # hell yeah 
    elsif response.code == 200 
    p "Success 200" 
    elsif response.code == 404 
. puts "Could not get a sitemap, something's wrong." 
    else 
    p "check your input!!!!" 
end 

回答

1

的HTTP響應狀態代碼301。此狀態代碼應與 位置標題一起使用。 RFC 2616規定:

If a client has link-editing capabilities, it should update all references to the Request URI. 
The response is cachable. 
Unless the request method was HEAD, the entity should contain a small hypertext note with a hyperlink to the new URI(s). 
If the 301 status code is received in response to a request of any type other than GET or HEAD, the client must ask the user before redirecting. 

我不認爲它公平爲你假設一個301響應表明,曾經有過一個網站地圖。如果您檢查sitemap.xml或站點地圖目錄的存在,那麼預期的正確響應是2XX。

如果您堅持假設3XX請求指示重定向到站點地圖,則請按照重定向並添加邏輯來檢查頁面的URL(如果其主頁)或頁面的內容以查看如果它具有XML結構。

+0

非常感謝Sunny的幫助。 –

0

Sitemap也可能被壓縮爲sitemap.xml.gz - 因此您可能還需要檢查該文件名。此外,它可能有一個索引文件指向許多其他的子站點地圖,這些站點地圖的名稱也可能不同。

對於我的項目的例子,我有:

sitemap_index.xml.gz 
    -> sitemap_en1.xml.gz (english version of links) 
    -> sitemap_pl1.xml.gz (polish version of links) 
    -> images_sitemap1.xml.gz (only images sitemap) 

與文件名網站坪的搜索引擎,但有時他們也可以包括他們在/robots.txt文件,所以你可以嘗試在那裏追捕他們。例如http://google.com在其文件的末尾有這樣:

(見網站地圖的名字如何怪異都可以!)

Sitemap: http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml 
Sitemap: http://www.google.com/hostednews/sitemap_index.xml 
Sitemap: http://www.google.com/ventures/sitemap_ventures.xml 
Sitemap: http://www.google.com/sitemaps_webmasters.xml 
Sitemap: http://www.gstatic.com/trends/websites/sitemaps/sitemapindex.xml 
Sitemap: http://www.gstatic.com/dictionary/static/sitemaps/sitemap_index.xml 

關於301:您可以嘗試欺騙的谷歌機器人或其他履帶。也許他們重定向除了機器人以外的所有人但是,如果他們重新引導每個人,那麼你無法對此做任何事情。

+0

我明白了你的觀點,謝謝,但是還有其他方法可以爲我的案例取得確鑿的結果嗎? –

+0

如果你的情況下你的意思是301響應代碼,那麼,不是真的。就像@ sunny-j解釋的那樣。當然,你可能不想與普通用戶分享一些東西,所以_maybe_這是一個網站地圖。 –

+0

Thanks.Yeah我明白了@ Sunny的回覆301迴應代碼。就我的情況而言,我的意思是,這個問題有其他解決方案嗎? –