【问题标题】:rvest scraping data with different lengthrvest 抓取不同长度的数据
【发布时间】:2021-02-09 06:32:44
【问题描述】:

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

这里是抓取的代码:

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 填充价格变量?

【问题讨论】:

标签: r web-scraping rvest


【解决方案1】:

网页检查显示当价格有值时类是.price,当没有值时是.price-txt。所以一种解决方案是在html_nodes() 中使用XPath 表达式并匹配以“price”开头的类:

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

length(listed_price)
[1] 60

【讨论】:

  • 非常感谢您的帮助,效果很好。我需要了解更多关于 xpath 的信息,你有没有关于 xpath 的好资料?谢谢你!
  • 我使用 CSS 选择器多于 XPath,但在这种情况下它很有用。除了 Google 搜索之外,我没有任何特别的建议 :) 也许是 this is a good start point
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2018-09-03
  • 2015-08-23
相关资源
最近更新 更多