通过rcurl抓取网页数据

 

获取数据有多种方式,例如从txt、excel、curl、数据库等,我比较喜欢curl和数据库,先介绍下rcurl

一 下载rcurl包
http://cran.r-project.org/web/packages/RCurl/index.html

二 安装 

sudo R CMD INSTALL RCurl_1.95-4.1.tgz

  

三 试运行

出错,发现缺少另外一个包,bitops

四 安装bitops


http://cran.r-project.org/web/packages/bitops/index.html

运行 

sudo R CMD INSTALL bitops_1.0-6.tgz

 



五 安装XML包
从网上看到的实例都需要这个包,怎么 办?安吧

下载地址:http://cran.r-project.org/web/packages/XML/index.html
命令行输入:

sudo R CMD INSTALL XML_3.98-1.1.tgz

 



傻了,命名可以直接在R下输入install命令的

六 安装了RJSONIO包
使用R内置的install命令安装失败,继续老办法安装后,成功

七 实例
获取豆瓣里冰雪奇缘影片的评分,代码如下:

library(RCurl)
library(XML)
library(RJSONIO)
movieScoreapi <- function(x) {
api <- "https://api.douban.com/v2/movie/search?q={"
url <- paste(api, x, "}", sep = "")
res <- getURL(url)
reslist <- fromJSON(res)
name <- reslist$subjects[[1]]$title
score <- reslist$subjects[[1]]$rating$average
return(list(name = name, score = score)) }
movieScoreapi('冰雪奇缘’)

  



运行成功

posted @ 2014-05-13 15:44  jiamei  阅读(878)  评论(0编辑  收藏  举报