2010-03-23 58 views

回答

16

下面是一個快速和骯髒的解決方案,而應把工作做好:

library(RCurl) 

decode.short.url <- function(u) { 
    x <- try(getURL(u, header = TRUE, nobody = TRUE, followlocation = FALSE)) 
    if(class(x) == 'try-error') { 
    return(u) 
    } else { 
    x <- strsplit(x, "Location: ")[[1]][2] 
    return(strsplit(x, "\r")[[1]][1]) 
    } 
} 

變量 'U' 下面包含一個URL shortend,和一個普通的URL。

u <- c("http://tinyurl.com/adcd", "http://www.google.com") 

然後,您可以通過執行以下操作獲取擴展結果。

sapply(u, decode.short.url) 

以上應該適用於大多數縮短網址的服務,而不僅僅是tinyURL。我認爲。

HTH

託尼Breyal

1

我不知道R,但一般來說你需要向tinyurl-url發出http請求。你應該得到一個301迴應與實際的網址。

0
library(RCurl) 

decode.short.url <- function(u) { 
    x <- try(getURL(u, header = TRUE, nobody = TRUE, followlocation = FALSE)) 
    if(class(x) == 'try-error') { 
    return(u) 
    } else { 
    x <- strsplit(x, "Location: ")[[1]][2] 
    return(strsplit(x, "\r")[[1]][1]) 
    } 
} 


(u <- c("http://tinyurl.com/adcd", "http://tinyurl.com/fnqsh")) 
(sapply(u, decode.short.url)) 
+0

託尼,你有兩個帳戶? – 2010-03-25 15:18:45

+0

@ JD-Long是的,但我不知道如何合併這兩個賬戶。頂部的使用OpenID。我什至不記得如何登錄到底部的一個(與危險鼠標圖片)。我新來張貼在stackoverflow。 – 2010-04-09 10:12:21

1

我用託尼Breyal的代碼,但該函數返回NA值這裏沒有URL重定向這些網址。儘管託尼在他的例子中列出了「google.com」,但我認爲Google會將您重定向到google.com的某種本地化版本。

這是我如何修改託尼的代碼來處理是:

decode.short.url <- function(u) { 
    x <- try(getURL(u, header = TRUE, nobody = TRUE, followlocation = FALSE)) 
    if(class(x) == 'try-error') { 
    print(paste("***", u, "--> ERORR!!!!"))  
    return(u) 
    } else { 
    x <- strsplit(x, "Location: ")[[1]][2] 
    x.2 <- strsplit(x, "\r")[[1]][1] 
    if (is.na(x.2)){ 
     print(paste("***", u, "--> No change.")) 
     return(u) 
    }else{ 
     print(paste("***", x.2, "--> resolved in -->", x.2)) 
     return(x.2) 
    } 
    } 
} 


u <- list("http://www.amazon.com", "http://tinyurl.com/adcd") 
urls <- sapply(u, decode.short.url)