簡體   English   中英

R:Rvest - 同時獲取 2 個元素(節點)

[英]R: Rvest - getting 2 elements (nodes) at the same time

我正在做一些網頁抓取。

我需要獲取 actual_price,並將 old_price 放在另一列中。

問題是並非所有產品都有 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:

代碼重現情況。 它用於 Celulares 部分:

運行 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")

但我不知道如何提取問題所說的新舊價格。

歡迎任何提示。

#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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM