在R中解码tinyurl以获得完整的url路径?

时间:2010-03-23 14:58:41

标签: url r

有没有办法解码R中的tinyURL链接,以便我可以看到他们实际引用的网页?

4 个答案:

答案 0 :(得分: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'包含一个shortend url和一个常规url。

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

然后,您可以通过执行以下操作来获得扩展结果。

 sapply(u, decode.short.url) 

上述内容适用于大多数缩短URL的服务,而不仅仅是tinyURL。我认为。

HTH

Tony Breyal

答案 1 :(得分:1)

我不知道R但是一般来说你需要向tinyurl-url发出http请求。您应该使用实际网址获得301响应。

答案 2 :(得分:1)

我使用了Tony Breyal的代码,但该函数返回了那些没有URL重定向的URL的NA值。虽然Tony在他的例子中列出了“google.com”,但我认为Google无论如何都会将你重定向到google.com的某种本地化版本。

以下是我修改Tony代码以解决这个问题的方法:

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)

答案 3 :(得分: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) )