爬取中国票房网

浏览: 2082

这篇文章教大家如何抓取CBO中国票房网,首先使用XML包抓取电影票房数据,再通过正则表达式对数据进行清洗,最后对数据进行了可视化分析

1.加载所需R

library(XML)
library(ggplot2)
library(ggthemes)
knitr::opts_chunk$set(echo = TRUE)

2.抓取表格

url<-"http://www.cbooo.cn/year?year=2017"
doc<-htmlParse(url,encoding = "UTF-8")
tables<-readHTMLTable(doc)
table<-tables[[1]]

3.数据清洗

names(table) <- c("title", "type", "boxoffice", "meanprice", "numofpeople", "nation", "date")
boxdf <- as.data.frame(lapply(table, as.character), stringsAsFactors=FALSE)
boxdf[,1] <- sub(pattern="\\d{1,2}.", replacement="", table[,1])
boxdf <- cbind(rank = 1:25,boxdf)
col1 <- c(3,7)
col2 <- 4:6
boxdf[, col1] <- lapply(boxdf[,col1], as.factor)
boxdf[, col2] <- lapply(boxdf[,col2], as.numeric)
DT::datatable(boxdf)

image.png

4.可视化结果

ggplot(boxdf)+
geom_bar(aes(x=reorder(title, boxoffice), y=boxoffice, fill = "boxoffice"),
        position = "dodge",stat = "identity")+
  scale_fill_manual(values=c(boxoffice="#A6CEE3")) +
  coord_flip() + labs(x=NULL, y=NULL, title="2017年中国内地电影总票房Top25(单位:万)")+
 theme_economist_white()

image.png

typedata <- as.data.frame(table(boxdf$type))
names(typedata) <- c("type","number")
ggplot(typedata, aes(x=type, y =number, fill=type))+
geom_bar(position="dodge", stat="identity")+
geom_text(aes(label=number), hjust=0.5, vjust=-0.5, size=5) +
labs(x="电影类型",y="影片数", title="2017年中国内地电影票房Top25的电影类型分布")+
theme_economist()

image.png


推荐 0
本文由 EasyCharts 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

1 个评论

> tables<-readHTMLTable(doc)
Error in make.names(vnames, unique = TRUE) : invalid multibyte string 6
运行时这个错误时什么意思

要回复文章请先登录注册