【发布时间】:2019-06-27 15:46:31
【问题描述】:
我正在为教育目标抓取网页。
我得到了这些值:producto(产品)、precio_antes(price_before)、precio_actual(price_now)和marca(品牌)。
我得到了正确的产品,但是:
-
precio_antes当价格不同时,所有商品均返回 S/1,399.00 -
precio_actual为所有项目返回 NA。 -
marca为所有项目返回“lg”。
预期输出:
| ecommerce | marca | producto | precio_antes | precio_actual | |
|-----------|-------|------------------------------------------|--------------|---------------|---|
| wong | lg | LG Smart TV 49" Full HD 49LK5400 | S/1,399.00 | S/1,299.00 | |
| wong | lg | LG Smart TV 60" 4K UHD 60UK6200 ThinQ AI | S/2,599.00 | S/2,299.00 | |
当前输出
| ecommerce | marca | producto | precio_antes | precio_actual | |
|-----------|-------|------------------------------------------|--------------|---------------|---|
| wong | lg | LG Smart TV 49" Full HD 49LK5400 | S/1,399.00 | NA | |
| wong | lg | LG Smart TV 60" 4K UHD 60UK6200 ThinQ AI | S/1,399.00 | NA | |
我正在使用RSelenium,我认为我的 CSS 选择器技能需要变得更好。
library(RSelenium)
library(rvest)
library(dplyr)
library(stringr)
#start RSelenium
rD <- rsDriver(port = 4570L, browser = "chrome", version = "latest", chromever = "75.0.3770.90",
geckover = "latest", iedrver = NULL, phantomver = "2.1.1",
verbose = TRUE, check = TRUE)
remDr <- rD[["client"]]
#navigate to your page
remDr$navigate("https://www.wong.pe/tecnologia/televisores/tv")
#scroll down 10 times, waiting for the page to load at each time
for(i in 1:10){
remDr$executeScript(paste("scroll(0,",i*10000,");"))
Sys.sleep(3)
}
#get the page html
page_source<-remDr$getPageSource()
product_info <- function(node){
precio_antes <- html_nodes(node, 'span.product-prices__value') %>% html_text
precio_actual <- html_nodes(node, 'span.product-prices__value product-prices__value--best-price') %>% html_text
marca <- html_nodes(node,"p.brand") %>% html_text
producto <- html_nodes(node,"a.product-item__name") %>% html_text
precio_antes <- gsub("\\S\\/\\. ", "", precio_antes)
precio_actual <- gsub("\\S\\/\\. ", "", precio_actual)
data.frame(
ecommerce = "wong",
marca = ifelse(length(marca)==0, NA, marca),
producto = producto,
precio_antes = ifelse(length(precio_antes)==0, NA, precio_antes),
precio_actual = ifelse(length(precio_actual)==0, NA, precio_actual),
stringsAsFactors=F
)
}
doc <- read_html(iconv(page_source[[1]]), to="UTF-8") %>%
html_nodes("div.category-shelf-wrapper")
wong_tvs <- lapply(doc, product_info) %>%
bind_rows()
奖励:
我得到的西班牙字符的方式不正确,即使我正在使用:
LG Control Remoto Mágico AN-MR18BA #Should be Mágico
doc <- read_html(iconv(page_source[[1]]), to="UTF-8") %>%
html_nodes("div.category-shelf-wrapper")
为什么?
【问题讨论】:
-
我强烈建议不要结合多个问题。 “奖励”问题似乎比其他问题简单得多——我敢打赌,如果你把它作为一个单独的问题发布,你会很快得到答案。但是把它留在大问题的底部,你把它隐藏起来,阻止任何人回答,除非他们也能回答这个大问题。
-
您能否详细说明预期的输出。我部分理解了这个反面例子。一个积极的会很棒,谢谢!
-
@BigDataScientist,请查看原始问题中的更改。