【问题标题】:R URL encoding issue?R URL编码问题?
【发布时间】:2014-02-12 14:33:30
【问题描述】:

我正在尝试使用 RCurl 包从网站上获取数据表。我的代码成功地适用于您通过点击网站访问的 URL:

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

一旦您尝试选择前几年(我想要的);我的代码不再有效。

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

我猜这与年份特定地址中的保留符号有关。我试过 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

有谁知道问题是什么以及如何解决?

【问题讨论】:

  • 使用reserved=FALSE 会出现同样的错误吗?
  • 设置 reserved=FALSE 会导致 R 在执行 geturl 命令时挂起) : 'data' 必须是向量类型,为 'NULL'

标签: r urlencode


【解决方案1】:

跳过不需要的url编码和下载:

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

pagetree <- htmlTreeParse(url, useInternalNodes = TRUE)

【讨论】:

  • 这给了我错误Error in UseMethod("xmlNamespaceDefinitions") : no applicable method for 'xmlNamespaceDefinitions' applied to an object of class "NULL" 任何想法?
  • 我没有收到那个错误。所以这可能是 XML 中的一个错误,或者我们中的一个人没有最新版本的 XML。
  • 我也没有收到该错误。我在 Windows 8.1 上使用 XML ‘3.98.1.1’ 和“R version 3.0.2 Patched (2013-11-25 r64299)”。
猜你喜欢
  • 1970-01-01
  • 2011-10-14
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 2018-08-20
  • 2016-08-14
  • 2015-12-09
相关资源
最近更新 更多