首页 > 解决方案 > 将html_nodes转换为R中的数据框

问题描述

我正在从网页中提取数据

url <- "https://www.lacolonia.com/vinagre-tinto-carbonell-250-ml-ref8410010855064/p"

我想要一个 data_frame 中的所有数据

html <- read_html(url) #leyendo HTML
productos <- html_nodes(html,".product-details , .skuBestPrice") #extrayendo el HTML en bruto
links5 <- html_nodes(productos, "a")
links6 <- bind_rows(lapply(xml_attrs(links5), function(x) data.frame(as.list(x), stringsAsFactors=FALSE)))

链接没有来自“productos”的一些数据,缺少价格值

productos 为我提供此信息

[1] <div class="row product-details "><div class="">\n<div class="col-xs-12 hidden-sm description-prod"><div class="c ...
[2] <strong productindex="0" class="skuBestPrice">L. 75.90</strong>

我需要 data_frame 中的 value= 75.90,你能帮我写代码吗

标签: rrvest

解决方案


您可以使用 :

library(rvest)
url <- "https://www.lacolonia.com/vinagre-tinto-carbonell-250-ml-ref8410010855064/p"

url %>%
  read_html() %>%
  html_nodes('p.descricao-preco strong.skuBestPrice') %>%
  html_text() %>% 
  sub('.*?(\\d+\\.\\d+).*', '\\1', .) %>% as.numeric()
  #For optional decimal numbers 
  #sub('.*?(\\d+\\.?\\d?).*', '\\1', .) %>% as.numeric()

#[1] 75.9

推荐阅读