r - 使用 Rvest 进行网页抓取:将缺失的条目设置为 NA
问题描述
我是一个绝对的 R 初学者,我一直在尝试从Sprinter Sports 页面上获取鞋子的价格,最终目标是拥有一个每天自动加载 (i) 原始和 (ii) 折扣的数据集我感兴趣的鞋子的价格。
问题是,目前在售的 24 款鞋子中,只有 16 款同时拥有“原价”和“折扣”价格。其余 8 个没有“折扣”价格,因为它们没有以折扣价出售。由于“原始”列有 24 个观察值,而“折扣”列只有 16 个,因此我无法将它们连接到数据集中。
如何在没有折扣的情况下加载鞋子,以使它们的“折扣”列设置为 NA?我的代码如下。谢谢!
date_today = substring(gsub("-", "", Sys.Date()),3)
page_sp_merrel <- read_html("https://www.sprintersports.com/pt/sapatilhas-merrell-homem?page=1&per_page=50")
price_old_sp_merrel <- page_sp_merrel %>%
html_nodes(".product-card__info-price-old") %>%
html_text()
price_new_sp_merrel <- page_sp_merrel %>%
html_nodes(".product-card__info-price-actual") %>%
html_text()
product_name_sp_merrel <- page_sp_merrel %>%
html_nodes(".col-md-3 .product-card__info-name") %>%
html_text()
sp_merrel_df <- tibble(
price_old = price_old_sp_merrel,
price_new = price_new_sp_merrel,
product_name = product_name_sp_merrel,
date = date_today
)
解决方案
这可以像这样实现。基本上,我的方法与您的方法不同,因为我遍历卡片并将所需的信息直接提取到数据框中,NA
如果卡片上不存在元素,则会自动给出:
library(rvest)
date_today = substring(gsub("-", "", Sys.Date()),3)
page_sp_merrel <- read_html("https://www.sprintersports.com/pt/sapatilhas-merrell-homem?page=1&per_page=50")
sp_merrel_df <- page_sp_merrel %>%
html_nodes(".product-card__info-data") %>%
purrr::map_df(function(x) {
data.frame(
product_name = html_node(x, ".product-card__info-name") %>% html_text(),
price_old = html_node(x, ".product-card__info-price-old") %>% html_text(),
price_new = html_node(x, ".product-card__info-price-actual") %>% html_text(),
date = date_today
)
})
head(sp_merrel_df)
#> product_name price_old price_new date
#> 1 Merrell Riverbed 3 69,99 € 59,99 € 210719
#> 2 Sapatilhas Montanha Merrell <NA> 114,99 € 210719
#> 3 Merrell Moab Adventure <NA> 99,99 € 210719
#> 4 Merrel Moab 2 Vent 99,99 € 79,99 € 210719
#> 5 Merrell Alverstone <NA> 79,99 € 210719
#> 6 Merrell Chameleon <NA> 129,99 € 210719
推荐阅读
- php - 在 Laravel 中调用未定义函数 App\Http\Controllers\veiw() 错误
- linux - 连接到 http://br.archive.ubuntu.com/ubuntu 超时
- c# - 我的对称加密将数据添加到我想要保存并加载加密的 rsa 密钥
- typescript - X(具有函数和状态的 JS 对象)指的是一个值,但在这里使用的是一个类型
- c# - SqlException:当 IDENTITY_INSERT 设置为 OFF ASP.NET Core 2.1 时,无法在表“类别”中插入标识列的显式值
- javascript - 如何在 HTML5 画布中上传和显示 ppt
- multithreading - 为什么我不能在横梁范围内生成预定义的闭包
- python - 如何使用 beautifulsoup 遍历整个 web 表?
- c# - 如何使用 OpenXml C# 为 PPT 将段落居中对齐?
- java - 字符数组中的索引超出范围错误