首页 > 解决方案 > rvest 抓取不同长度的数据

问题描述

作为一个实践项目,我正在尝试从网站上抓取房产数据。(我只打算练习我的网络抓取技能,无意进一步利用抓取的数据)。但是我发现某些属性没有可用的价格,因此,当我尝试将它们组合到一个数据框中时,这会产生不同长度的错误。

这是抓取的代码:

library(tidyverse)
library(revest)

web_page <- read_html("https://wx.fang.anjuke.com/loupan/all/a1_p2/")

community_name <- web_page %>% 
  html_nodes(".items-name") %>% 
  html_text()

length(community_name)

listed_price <- web_page %>% 
  html_nodes(".price") %>% 
  html_text()

length(listed_price)
property_data <- data.frame(
  name=community_name,
  price=listed_price
)

当没有价值被刮掉时,如何识别没有列出价格的财产并用 NA 填充价格变量?

标签: rweb-scrapingrvest

解决方案


对网页的检查表明,.price当价格有价值时,该类是有价值的,而.price-txt当它没有价值时。因此,一种解决方案是使用 XPath 表达式html_nodes()并匹配以“price”开头的类:

listed_price <- web_page %>% 
  html_nodes(xpath = "//p[starts-with(@class, 'price')]") %>% 
  html_text()

length(listed_price)
[1] 60

推荐阅读