R语言爬虫实践(上):二手房数据采集

主要参考文章:[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")
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值