2

我正在做一些网页抓取。

我需要获取实际价格,并将旧价格放在另一列中。

问题是并非所有产品都有 old_price 元素,因为它们是新的。

而且由于它们的长度不同,我无法将它们加入 data.frame 中。

如果产品没有 old_price,我想在单元格中有 NA。

有没有办法用 Rvest 做到这一点?

预期结果:

Product      PriceNew        PriceOld
  A          2300.00            NA
  B          9.90              49.00
  C          1299.00           2499.00
  D          829.00            1499.00
  

![在此处输入图像描述][1]

如您所见,这是一个示例。一种产品有实际价格和旧价格,另一种没有。

我一直在这样做:

Celulares_Telefonia_Precio_actual <- html(page_source[[1]]) %>% 
                            html_nodes(".product-itm-price-new") %>%
                            html_text()

Celulares_Telefonia_Precio_antiguo <- html(page_source[[1]]) %>% 
                            html_nodes(".product-itm-price-old") %>%
                            html_text()

所有产品都有价格,但并非所有产品都有旧价格。因此,对于那些只有新价格的产品,我希望在 Old_Price 列中有 NA。

  length(Celulares_Telefonia_Precio_actual)  gives 120

  length(Celulares_Telefonia_Precio_antiguo)  gives 114 

编辑1:

重现情况的代码。它适用于 Ceulares 部分:

请运行 Gist 以获取我的数据:

library(devtools)
source_gist("https://gist.github.com/OmarGonD/b70b712327d7e479f2c7")

编辑2:

我试过查看整个容器(产品品牌、产品名称、新价格、旧价格)。使用 SelectorGadget 我看到整个容器是:("#catalog-items"如果我错了,请纠正我)。

所以我使用:

    Celulares_Telefonia_Catalogo <- html(page_source[[1]]) %>%
  html_nodes("#catalog-items")

但我不知道如何提取问题所说的新旧价格。

欢迎任何提示。

4

1 回答 1

0
#This may be one solution
library(rvest)
kk1<-html("http://www.linio.com.co/tecnologia/celulares-telefonia-gps/")%>%
   html_nodes(".product-item-price")%>%
   html_text()
#remove spaces
kk2<-gsub("\\s+","",kk1)
#strsplit kk2
kk3<-strsplit(kk2,"\\$|\\-|Nuevo")
#convert to dataframe
kk4<-do.call(rbind,kk3)
kk5<-kk4[,2:3] # column 2 gives you new and column 3 gives you old (blank for no old price)

head(kk5)
     [,1]        [,2]       
[1,] "750.000"   "549.900"  
[2,] "999.900"   "579.900"  
[3,] "2.019.900" "1.729.900"
[4,] "2.399.900" "2.299.900"
[5,] "1.899.000" "1.099.900"
[6,] "2.500.000" "1.799.900"
于 2015-05-04T01:09:32.547 回答