爬虫简单来说就是利用Html、css等前端规范形式,模拟人工手动搜集数据的方式获取数据。
R语言爬虫包Rvest,能够非常方便的爬取一些简单的网页。
Rvest包
安装
install.packages('rvest')
常用功能
函数 | 描述 |
---|---|
read_html() | 下载网页 |
html_nodes() | 获得指定名称的网页元素、节点 |
html_text() | 获得指定名称的网页元素、节点文本 |
html_table() | 获取table标签中的表格,默认参数trim=T,header=T为包含表头。结果返回数据框 |
基本步骤
- 爬取整张网页
- 查找所需内容处在节点
- 爬取相关内容
简单实例
- 使用谷歌浏览器
- 在谷歌商店搜索安装SelectorGadget插件,这个插件方便快速找出节点。
- SelectorGadget使用
- 安装之后点击浏览器右上角插件。
- 选中需要爬取的内容,右键检查。
- 记录节点位置。
在新浪地产网爬取房地产土地资讯内容(仅出于学习目的)
网站地址http://youcaiyun.com/News/5
#载入rvest包
library(rvest)
#网站地址url
url <- 'http://youcaiyun.com/News/5'
#使用read_html()获取网页
cont <- read_html(url)
#使用html_nodes()解析网页
#由SelectorGadget环节可知
#标题在.desc h1节点,内容在.desc p节点
title <- html_nodes(cont,'.desc h1')
text <- html_nodes(cont,'.desc p')
#使用html_text()提取内容
tit <- html_text(title)
txt <- html_text(text)
#可以看到内容存在换行符号及大量空白
#使用stringr包去除空白
library(stringr)
tit <- str_trim(tit)
txt <- str_trim(txt)
#储存数据
data <- data.frame(tit,txt)
View(data)