0
点赞
收藏
分享

微信扫一扫

Scraping data from the web R语言网络抓取

Mhhao 2022-01-28 阅读 58

工具 rvest

rvest:

  • 直接处理和操作 HTML 数据
  • 它旨在与使用 %>% 构建的管道一起使用

rvest核心函数:

  • read_html 从 url 或字符串中读取 HTML 数据
  • html_node 从 HTML 文档中选择一个指定的节点
  • html_nodes 从 HTML 文档中选择特定节点
  • html_table 将 HTML 表格解析为data frame
  • html_text 提取标签对的内容
  • html_name 提取标签名称
  • html_attrs 提取每个标签的所有属性
  • html_attr 按名称提取标签的属性值

实例:Glasgow房价

URL: https://nethouseprices.com/house-prices/Lanarkshire/GLASGOW
安装包

install.packages("robotstxt")
install.packages("tidyverse")
install.packages("rvest")
install.packages("stringr")

1 检查许可

library(robotstxt)
paths_allowed("http://www.imdb.com")

2 读取整页

  • 读取整页为page
page <- read_html("https://nethouseprices.com/house-prices/Lanarkshire/GLASGOW")
page

在这里插入图片描述

  • page 属性
## 类型
typeof(page)

在这里插入图片描述

class(page)

在这里插入图片描述

3 提取元素

  • 地址
    利用SelectorGadget
    Chrome Extension - SelectorGadget
    在这里插入图片描述
name <- page %>%
  html_nodes("strong a")

在这里插入图片描述

titles <- page %>%
  html_nodes(".titleColumn a") %>%
  html_text()  ## 提取文字,并储存在titles里
titles

在这里插入图片描述

  • 房屋类型
type <- page %>%
  html_nodes(".street-details-row") %>%
  ## 提取文字,并储存在titles里
  html_text()  
type
  • 房屋价格
price <- page %>%
  html_nodes(".street-details-price-row") %>%
  ## 提取文字,并储存在titles里
  html_text() #%>%
price  

在这里插入图片描述
逗号正常用str_remove()去除,但是这里英镑符号有点难去除,str_remove系列和gsub()都无法实现。

x = c("£3","4£")
gsub("£","",x)

在这里插入图片描述
在这里插入图片描述
对比发现是两种英镑符号不一样
在这里插入图片描述
没有更快的解决办法了直接简单粗暴循环,利用str_sub()去除每个字符串的第一位(感谢这次数据结构十分整齐)

i=1
while (i <= length(price)){
  price[i]=str_sub(price[i],2)
  i=i+1
}

整合进tibble

glasgow_house_price3 <- tibble(
  address = name,
  prices = as.numeric(price),
  types = type
)
举报

相关推荐

0 条评论