主要参考文章:[1][https://www.jianshu.com/p/c092d57d275f]
[2]https://blog.csdn.net/u013421629/article/details/76803903?locationNum=8&fps=1
gurl <- "http://sh.ganji.com/wblist/jingan/ershoufang/pn2/"
getData <- function(gurl){
# 抓取赶集网二手房源单页的数据
library(rvest)
# 赶集网首页筛选上海静安区的二手房源,获得链接,o1为页数
tmp <- gurl %>% html_session %>%
read_html(encoding="utf-8") %>%
html_nodes("div.f-main-list>div>div")
# 单个房源的puid
puid <- tmp %>% html_attr("puid")
# 单个房源的链接
itemURL <-tmp %>% html_attr("href") %>% gsub(pattern="/fang5",replacement="http://cs.ganji.com/fang5")
# 缩略图链接
smallImg <- tmp %>% html_nodes("dl>dt>div>a>img") %>% html_attr("src")
# 标题
iTitle <- tmp %>% html_nodes("dl>dd>a") %>% html_attr("title")
# 户型--改动
#路径:f_mew_list > div.f-main.f-clear.f-w1190 > div.f-main-left.f-fl.f-w980 > div.f-main-list > div > div:nth-child(1) > dl > dd.dd-item.size > span:nth-child(1)
iLayout <- tmp %>% html_nodes("dl > dd.dd-item.size > span:nth-child(1)") %>% html_text
# 面积--改动
#路径:f_mew_list > div.f-main.f-clear.f-w1190 > div.f-main-left.f-fl.f-w980 > div.f-main-list > div > div:nth-child(1) > dl > dd.dd-item.size > span:nth-child(3)
iArea <- tmp %>% html_nodes("dl > dd.dd-item.size > span:nth-child(3)") %>% html_text
# 筛选朝向等数据
iOrientation<- tmp %>% html_nodes("dl > dd.dd-item.size > span:nth-child(5)") %>% html_text# 提取朝向
iFloor <- tmp %>% html_nodes("dl > dd.dd-item.size > span:nth-child(7)") %>% html_text# 提取楼层
# 提取地址
iAddr <- tmp %>% html_nodes("dl>dd>span.area") %>% html_text %>% gsub(pattern="\n",replacement=" ") %>% gsub(pattern=" ",replacement="")
# 提取价格
iPrice <- tmp %>% html_nodes("dl>dd>div.price>span:first-child") %>% html_text
# 提取单价
iunitPrice <- tmp %>% html_nodes("dl>dd>div.time") %>% html_text %>% gsub(pattern="[^0-9]",replacement="") %>% as.numeric
# 合并数据框
iData <- data.frame(puid=puid,
iLayout=iLayout,
iArea=iArea,
iPrice=iPrice,
iunitPrice =iunitPrice ,
iFloor=iFloor,
iOrientation=iOrientation,
itemURL=itemURL,
smallImg=smallImg,
iTitle=iTitle,
iAddr=iAddr,
stringsAsFactors=FALSE)
# 返回数据框
return(iData)
}
result <- getData(gurl)
write.csv(result,"d:/jingan02.csv")