RStudio 公司就是给力,即dplyr终结了plyr后,现在又推出rvest,看样子多做爱(XML)也要阳痿了。
下面用抓取豆瓣网电影数据为例,演示一下它的便捷。
library(rvest)
url = 'http://movie.douban.com/top250?format=text'
web = html(url,encoding="UTF-8")
score = html_text(web %>% html_nodes("span") %>% html_nodes("em"))
year = web %>% html_nodes("p")
year = html_text(year[seq(1,50,2)])
gy = gregexpr('[0-9]{4}',year)
gd = gregexpr("导演",year)
gz = gregexpr("主演",year)
time = sapply(1:length(gy),function(i) substr(year[i],gy[[i]],gy[[i]]+attr(gy[[i]],'match.length')-1))
direct = sapply(1:length(gy),function(i) substr(year[i],gd[[i]] + 4,gz[[i]] - 4))
actor = sapply(1:length(gy),function(i) substr(year[i],gz[[i]] + 4,gy[[i]] - 4))
ga = gregexpr('\n',actor)
actor = sapply(1:length(gy),function(i) substr(actor[i],1,ga[[i]] - 1))
names = web %>% html_nodes("img") %>% html_attr("alt")
names = iconv(names,"utf-8","gbk")
rates = html_text(web %>% html_nodes("span"))
rates = rates[grep("人评价",rates)]
rates = gsub("人评价","",rates)
movie = data.frame(电影 = names,时间 = time,得分 = score,评价人数 = rates,导演 = direct,主演 = actor)
head(movie)
电影 时间 得分 评价人数 导演 主演
1 肖申克的救赎 1994 9.6 575452 弗兰克·德拉邦特 Frank Darabont 蒂姆·罗宾斯 Tim Robbins /...
2 这个杀手不太冷 1994 9.4 545412 吕克·贝松 Luc Besson 让·雷诺 Jean Reno / 娜塔丽·波特曼 ...
3 阿甘正传 1994 9.4 486164 Robert Zemeckis Tom Hanks / Robin Wright Penn / Gary Sinise
4 霸王别姬 1993 9.4 390568 陈凯歌 Kaige Chen 张国荣 Leslie Cheung / 张丰毅 Fengyi Zha...
5 美丽人生 1997 9.4 266453 罗伯托·贝尼尼 Roberto Benigni 罗伯托·贝尼尼 Roberto Beni...
6 海上钢琴师 1998 9.2 427455 朱塞佩·托纳多雷 Giuseppe Tornatore 蒂姆·罗斯 Tim Roth / ...