我想解析这个 HTML: 并从中获取这个元素:
a) p
标签,带有 class: "normal_encontrado"
。
b) div
与 class: "price"
。
有时,某些产品中不存在 p
标签。如果是这种情况,则应将 NA
添加到从该节点收集文本的向量中。
这个想法是有 2 个长度相同的向量,然后将它们连接起来形成 data.frame
。有任何想法吗?
HTML部分:
<html>
<head></head>
<body>
<div class="product_price" id="product_price_186251">
<p class="normal_encontrado">
S/. 2,799.00
</p>
<div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
S/. 2,299.00
</div>
</div>
<div class="product_price" id="product_price_232046">
<div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
S/. 4,999.00
</div>
</div>
</body>
</html>
代码:
library(rvest)
page_source <- read_html("r.html")
r.precio.antes <- page_source %>%
html_nodes(".normal_encontrado") %>%
html_text()
r.precio.actual <- page_source %>%
html_nodes(".price") %>%
html_text()
最佳答案
如果未找到该标签,则 rvest 返回一个字符 (0)。因此,假设您将在每个 div.product_price 中最多找到一个当前价格和一个常规价格,您可以使用以下命令:
pacman::p_load("rvest", "dplyr")
get_prices <- function(node){
r.precio.antes <- html_nodes(node, 'p.normal_encontrado') %>% html_text
r.precio.actual <- html_nodes(node, 'div.price') %>% html_text
data.frame(
precio.antes = ifelse(length(r.precio.antes)==0, NA, r.precio.antes),
precio.actual = ifelse(length(r.precio.actual)==0, NA, r.precio.actual),
stringsAsFactors=F
)
}
doc <- read_html('test.html') %>% html_nodes("div.product_price")
lapply(doc, get_prices) %>%
rbind_all
编辑: 我误解了输入数据,因此将脚本更改为仅适用于单个 html 页面。
关于r - 使用 rvest 抓取 - 当标签不存在时使用 NAs 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250826/