原文链接:http://xccds1977.blogspot.com/2013/06/r.html(需翻墙)
1.方法一:
library("RCurl")
library(XML)
movieScore <- function(x) {
stopifnot(is.character(x)) #若不为tru,则调用stop
# 提交搜索豆瓣表单
search <- getForm("http://movie.douban.com/subject_search", search_text = x) #search_text与x是name-value参数
searchweb <- htmlParse(search)#当content确定为HTML时,可使用htmlTreeParse
# 解析搜索结果页面
resnodes <- getNodeSet(searchweb, "//div[@id='wrapper']//table[1]//a") #getNodeSet查找XML中的nodes
if (is.null(resnodes))
return(NULL) else resurl <- xmlGetAttr(resnodes[[1]], name = "href")
# 得到影片页面后第二次解析
resweb <- getURL(resurl, .encoding = "UTF-8")
content <- htmlParse(resweb, encoding = "UTF-8")
resnodes <- getNodeSet(content, "//div[@id='interest_sectl']//p[@class='rating_self clearfix']//strong")
namenodes <- getNodeSet(content, "//div[@id='content']//h1//span")
# 得到影片评分
score <- xmlValue(resnodes[[1]])
name <- xmlValue(namenodes[[1]])
return(list(name = name, score = score))
}
movieScore("素媛")
2.方法二:
library(RJSONIO)
library(RCurl)
library(XML)
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("辩护人")
3.网页数据抓取的步骤:
如果你对R不大熟悉,抓取这些表格也有更方便的法子,就是利用Chrome的扩展。有两个扩展值得推荐使用:一个扩展叫作table capture,它会自动找出网页中的若干表格,你只需选择所需的那个将其拷贝到剪贴板即可,然后再用下面的命令就可以读入到R中。
data <- read.table('clipboard',T)
另一个扩展叫作scraper。先选择你所需要的部分内容,然后右键选择scraper similar也能抓取表格,不过它会存到一个google doc中去。在天朝这玩意儿不大方便。
有些数据不是以表格方式出现的,例如用XML或是JSON方式储存的数据。在R中都有对应的包来处理。下面的示例即是用XML包来处理XML数据。在此之先你需要有一点关于XML和XPath的知识,首先处理的对象是这样一个页面:http://www.w3schools.com/xml/plant_catalog.xml
library(XML) xml.url <- "http://www.w3schools.com/xml/plant_catalog.xml" # 解析xml页面 xmlfile <- xmlTreeParse(xml.url) # 观察对象属性 class(xmlfile) # 获取根结点 xmltop <- xmlRoot(xmlfile) # 用xmlValue函数获取叶结点处的值 xmlValue(xmltop[[1]][[1]]) xmlValue(xmltop[['PLANT']][['COMMON']]) # xmlSApply类似于sapply函数,取出第一个子结点中的所有叶结点值 xmlSApply(xmltop[[1]],xmlValue) # 进一步可以取出所有子结点中的叶结点值 plantcat <- xmlSApply(xmltop, function(x) xmlSApply(x, xmlValue)) # 将数据转为数据框 plantcat_df <- data.frame(t(plantcat),row.names=NULL) plantcat_df[1:5,1:4]
有时候会遇到更为复杂的XML页面,此时的节点内含有参数值。如果要获取这些数据则需要使用getNodeSet()函数配合xmlValue()函数。当遇到更为复杂的数据,那我们只能用readLines读进来,再用字符串函数配合正则表达式来加以处理了。