r - 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 填充价格变量?
解决方案
对网页的检查表明,.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
推荐阅读
- python - Scipy minimise,如何获取一个 int 值数组作为输出
- java - 如何更改 Heroku 应用程序的默认架构?
- chrony - 在 Chrony 中启用 tempcomp
- android - 禁用缩放底部导航菜单android studio的活动项目
- mysql - 筛选选择是否比获取所有行然后筛选更快
- postgresql - 使用 express.js 时无法将新查询插入 Postgres 数据库
- javascript - 填写对象数组以添加 0 个值
- activecollab - 如何在 ActiveCollab 中通过 API 发送发票?
- linux - Flutter:AdbConnectionClientInfo 缺少可配置的必填字段
- node.js - Swift Alamofire 在 cookie 中设置用户对象