密切关注你的方法,这样做就可以了:
library(rvest)
u <- "http://www.falabella.com.pe/falabella-pe/category/cat40536/Climatizacion?navAction=push"
doc <- html(u)
Climatizacion_marcas1 <- doc %>%
html_nodes(".marca")[[1]] %>%
html_nodes("a") %>%
html_attr("title")
Climatizacion_producto1 <- doc %>%
html_nodes(".detalle") %>%
html_nodes("a") %>%
html_attr("title")
“\n\t\t”等来自html的解析。显然,里面有回车符和制表符。一个简单的解决方案是:
Climatizacion_precio1 <- doc %>%
html_node(".precio1") %>%
html_text() %>%
stringr::str_extract_all("[:number:]{1,4}[.][:number:]{1,2}", simplify = TRUE) %>%
as.numeric
Climatizacion_precio1
[1] 44.9
事实上,这从字符串中选取数字(因此也删除了“S/.”。如果您希望保留“S/.”,您可以执行以下操作:
Climatizacion_precio1 <- doc %>%
html_node(".precio1") %>%
html_text() %>%
gsub('[\r\n\t]', '', .)
Climatizacion_precio1
[1] "S/. 44.90"
EDIT这是另一种方法,使用XML
and selectr
。这将一次性获取页面上所有项目的信息。
library(XML)
clean_up <- function(x) {
stringr::str_replace_all(x, "[\r\t\n]", "")
}
product <- selectr::querySelectorAll(doc, ".marca") %>%
xmlApply(xmlValue) %>% lapply(clean_up) %>% unlist
details <- selectr::querySelectorAll(doc, ".detalle a") %>%
xmlApply(xmlValue) %>%
unlist
price <- selectr::querySelectorAll(doc, ".precio1") %>%
xmlApply(xmlValue) %>% lapply(clean_up) %>% unlist
as.data.frame(cbind(product, details, price))
product details price
1 Imaco Termoventilador NF15... S/. 44.90
2 Imaco Ventilador de 10" I... S/. 69
3 Imaco Ventilador Imaco de ... S/. 89
4 Taurus Recirculador TRA-30 ... S/. 89
5 Imaco Termoventilador ITC-... S/. 109
6 Sole Termo Ventilador Elé... S/. 99
7 Taurus Ventilador TVP-40 3 ... S/. 99
8 Imaco Estufa OFR7AO 1.500 ... S/. 129
9 Alfano Ventilador Recircula... S/. 139
10 Taurus Ventilador TVC-40RC ... S/. 139
11 Imaco Ventilador Pedestal ... S/. 149
12 Alfano Ventilador Orbital 1... S/. 149
13 Electrolux Ventilador de Mesa ... S/. 149.90
14 Alfano Estufa Termoradiador... S/. 159
15 Alfano Ventilador Pared 18"... S/. 169
16 Imaco Termoradiador OFR9AO S/. 179
您通常可能想要对结果进行一些初步清理。