大家好,我是上周末放鸽子了的菜鸟君。感谢大家耐心等待,今天来篇爬虫的攻略吧。
首先,需要一键安装以下R packages。对了,先隆重介绍R包“pacman”,你是不是经常被各种library浪费多行代码?是不是总被没有安装的R包打断思路?这个pacman包,一键解决以上问题!安装过的R包,就给你加载(相当于library功能);没安装过的R包,就帮忙下载安装(相当于install.packages功能)。
install.packages("pacman") #先安装这个包,方便一键加载其他包pacman::p_load(XML,rvest,dplyr,stringr)
好了正式进入爬虫主题:
house_inf <- data.frame()#爬取前50页for (i in 1:50){#发现url规律,利用字符串函数进行url拼接并规定编码:web <- read_html(str_c("https://bj.lianjia.com/ershoufang/pg", 82), encoding = "UTF-8")#提取房名信息:house_name <- web%>%html_nodes(".item a")%>%html_text()house_name2 <- ifelse(nchar(house_name)>8,house_name,NA)house_name2 <- na.omit(house_name2)#提取房名基本信息并消除空格house_basic_inf <- web%>%html_nodes(".houseInfo")%>%html_text()house_basic_inf <- str_replace_all(house_basic_inf," ","")#提取二手房地址house_address <- web%>%html_nodes(".positionInfo a")%>%html_text()house_address <- str_replace_all(house_address," ","")house_address <- data.frame(matrix(house_address,ncol = 2,nrow = 30,byrow = T))house_qu <- house_address[,1]house_district <- house_address[,2]#提取二手房总价house_totalprice <- web%>%html_nodes(".totalPrice")%>%html_text()#提取二手房单价house_unitprice <- web%>%html_nodes(".unitPrice span")%>%html_text()#创建数据框存储以上信息house<-data.frame(house_name2,house_basic_inf,house_qu,house_district,house_totalprice,house_unitprice)house_inf <- rbind(house_inf,house)}
整个爬取的结果,存储在house_inf这个数据集里。接下来,咱们进行一些简单的数据处理工作。主要包括去除无效字符、将房价进行从小到大的排列,毕竟我们最关注的还是便宜房源,对吧?如果有土豪朋友想关注高端房源,也可以从大到小排列(土豪我们交个朋友吧!)
#去除总价里除了数字以外的其他文字字符house_inf <- na.omit(house_inf)price <- house_inf$house_totalpriceprice <- stringr::str_remove_all(as.character(price), "[^0-9]")house_inf$price <- as.numeric(price)#按房价总价进行排序house_inf2 <- house_inf[order(house_inf[,7]),]#去掉重复的房价信息house_inf2 <- house_inf2[!duplicated(house_inf2),]#将结果存为csv格式,存储路径需要自行修改哦write.csv(house_inf2, file="price.csv",row.names = F)
我们简单画个图来看看房价分布的情况。目前主要为了探索数据,如果觉得太丑了,大家可以用ggplot2包来画的更美一些~欢迎在QQ群里晒一下你的美图!
plot(house_inf2$price)

这么看起来,咱们获取的房价从200W到600W+都有。为了更清晰的看到分布频率,我们看看柱状图。
hist(house_inf2$price)

这就能看出来,目前爬取的房价在200-300W之间分布的较多。
感兴趣的同学可以自行试试以上代码。当然了,我也注意到B站后台有小伙伴说,用R语言、for循环来干爬虫这事儿,太鸡肋了,效率上不能满足批量需求。没关系,只要大家感兴趣爬虫相关的分析,Python爬虫下次咱们就安排!下期再见嗷~
代码不报错,记得点“在看”
交流QQ群:83837564
B站:谁说菜鸟不会数据分析

