【R 語言爬蟲】rvest 包實戰鏈家爬蟲
阿新 • • 發佈:2019-02-07
rvest包簡介
rvest包是Hadley Wickham大神開發的一個專門用於網路資料抓取的R語言包,目前的發行版本為0.3.2,關於rvest包的描述以及用法可參考rvest幫助文件,花上一點時間閱讀幫助文件,相信你就可以寫出自己的爬蟲了。
help(package=“rvest”)
csdn中文版版:
R語言鏈家爬蟲:
#載入所需的包
rm(list=ls())
library("xml2")
library("rvest")
library("dplyr")
library("stringr")
#對爬取頁數進行設定並建立資料框
i<-1:10
house_inf<-data.frame()
#使用for 迴圈進行批量資料爬取(發現url的規律,寫for迴圈語句)
for (i in 1:10){
web<- read_html(str_c("http://hz.lianjia.com/ershoufang/pg",i),encoding="UTF-8")
#用SelectorGadget定位節點資訊並爬取房名
house_name<-web%>%html_nodes(".houseInfo a")%>%html_text()
#爬取二手房基本資訊並消除空格
house_basic_inf<-web%>%html_nodes(".houseInfo" )%>%html_text()
house_basic_inf<-str_replace_all(house_basic_inf," ","")
#SelectorGadget定位節點資訊爬取地址
house_address<-web%>%html_nodes(".positionInfo a")%>%html_text()
#SelectorGadget定位節點資訊爬取總價
house_totalprice<-web%>%html_nodes(".totalPrice")%>%html_text()
#SelectorGadget定位節點資訊爬取單價
house_unitprice<-web%> %html_nodes(".unitPrice span")%>%html_text()
#建立資料框儲存以上資訊
house<-data_frame(house_name,house_basic_inf,house_address,house_totalprice,house_unitprice)
house_inf<-rbind(house_inf,house)
}
#將資料寫入csv文件
write.csv(house_inf,file="D:/house_inf.csv")
#總共抓取了鏈家杭州二手房100個頁面3000條房價資訊