使用sapply在R中刮取多个URL

时间:2014-09-15 10:29:41

标签: r

下午好,

感谢您帮我解决这个问题。

我有一个多个网址列表,我有兴趣抓取特定字段。

目前,我正在使用以下功能返回我对特定字段感兴趣的值:

dayViews <- function (url) {
  raw <- readLines(url)
  dat  <- fromJSON(raw)
  daily <- dat$daily_views$`2014-08-14` 
  return(daily)
}

如何将其修改为在多个网址列表中运行?我尝试在URL列表中使用sapply / lapply,但它给了我以下消息:

"Error in file(con, "r") : invalid 'description' argument" 

如果有人有任何建议,我将非常感激。

非常感谢,

1 个答案:

答案 0 :(得分:0)

做一些与你类似的事情,@ yarbaur,我读到了一个Excel电子表格,它保存了我想要抓取的集合的所有URL。它包含公司,URL和XPath的列。然后尝试类似这样的代码,我已经替换了我编写的变量名。但是,我没有使用JSON站点:

temp <- apply(yourspreadsheetReadintoR, 1,  
              function(x) {
                yourCompanyName <- x[1]
                yourURLS <- x[2]
                yourxpath <- x[3] # I also store the XPath expressions for each site

                fetch <- content(GET(yourURLS))
                locs <- sapply(getNodeSet(fetch, yourxpath), xmlValue)

                data.frame(coName=rep(yourCompanyName, length(locs)), location=locs)
              })