2014-02-12 46 views
1

我想要使用RCurl包獲取網站的數據表。我的代碼工作成功的網址,你直接點擊網站得到:R URL編碼問題?

http://statsheet.com/mcb/teams/air-force/game_stats/

一旦你嘗試選擇前幾年(我想);我的代碼不再有效。

實例鏈接: http://statsheet.com/mcb/teams/air-force/game_stats?season=2012-2013

我猜這事做與今年的具體地址保留符號(S)。我試過URLencode以及手動編碼的地址,但也沒有奏效。

我的代碼:

library(RCurl) 
library(XML) 

#Define URL 
theurl <-URLencode("http://statsheet.com/mcb/teams/air-force/game_stats?season=2012-  
2013", reserved=TRUE) 

webpage <- getURL(theurl) 
webpage <- readLines(tc <- textConnection(webpage)); close(tc) 

pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE) 

# Extract table header and contents 
tablehead <- xpathSApply(pagetree, "//*/table[1]/thead[1]/tr[2]/th", xmlValue) 
results <- xpathSApply(pagetree,"//*/table[1]/tbody/tr/td", xmlValue) 

content <- as.data.frame(matrix(results, ncol = 19, byrow = TRUE)) 

testtablehead <- c("W/L","Opponent",tablehead[c(2:18)]) 
names(content) <- testtablehead 

相關的錯誤是R返回:

Error in function (type, msg, asError = TRUE) : 
Could not resolve host: http%3a%2f%2fstatsheet.com%2fmcb%2fteams%2fair- 
force%2fgame_stats%3fseason%3d2012-2013; No data record of requested type 

有沒有人有一個想法是什麼問題,如何解決?

+0

使用'保留= FALSE'給出了同樣的錯誤? – celiomsj

+0

Putting reserved = FALSE導致R在執行geturl命令時掛起 更新:實際上耗盡了該時間,但給出了錯誤: 矩陣中的錯誤(results,ncol = 19,byrow = TRUE): '數據'必須是矢量類型,爲'NULL' – Peter

回答

1

跳過網址的不必要的編碼和下載:

library(XML) 
url <- "http://statsheet.com/mcb/teams/air-force/game_stats?season=2012-2013" 

pagetree <- htmlTreeParse(url, useInternalNodes = TRUE) 
+0

這給了我錯誤'Error in UseMethod(「xmlNamespaceDefinitions」): 沒有適用於'xmlNamespaceDefinitions'的方法應用於類「NULL」對象任何想法? – Peter

+0

我不明白這個錯誤。所以這可能是XML中的一個錯誤,或者我們中的一個沒有最新版本的XML。 – hadley

+0

我也沒有得到那個錯誤。我在Windows 8.1上使用XML'3.98.1.1'和'R version 3.0.2 Patched(2013-11-25 r64299)「。 –