Очистка rvest данных заменой отсутствующего html_node на NA - PullRequest
0 голосов
/ 03 апреля 2020

Привет всем!

В течение достаточно долгого времени я пытался очистить данные и каким-то образом заменить отсутствующие html_nodes на NA или что-то еще. Тем не менее, я был неудачным.

Может кто-нибудь помочь мне разобраться, как это сделать? Или где посмотреть, чтобы понять, как это сделать?

Мой текущий код для очистки выглядит следующим образом:

library('rvest')
header_bind <- c()
page <- 0
price <- c()
ebay <- c()
runtime <- c()
pages <- 2
for (i in 1:pages) {


    page <- page + 1
    link <- paste("https://www.ebay.com/b/Cell-Phones-Smartphones/9355/bn_320094?LH_BIN=1&LH_ItemCondition=1000&rt=nc&_from=R40&_pgn=",page, sep="")
    webpage <- read_html(link)


    #read the name of the item
    header <- html_nodes(webpage, ".s-item__title")
    header_Text <- html_text(header)

      header_bind <- rbind(header_bind,as.data.frame(header_Text))

    #i get the price
    prim_html <- html_nodes(webpage, ".s-item__price")
    text_prim <- html_text(prim_html)

      price <- rbind(price,as.data.frame(text_prim))

    #i get the (amount sold this is missing sometimes)
    runtime_html <- html_nodes(webpage, ".NEGATIVE")
    text_runtime <- html_text(runtime_html)

      runtime <- rbind(runtime,as.data.frame(text_runtime))

    #prints 0 so i know that it went throught the for(){}
    print(0)
}

Ps Я знаю, что это выглядит плохо, но я узнавая каждый день, как лучше кодировать.

Код выводит 48 аксов за цену и название продукта, однако, когда дело доходит до проданного или оставшегося количества, это дает мне 43.

Я попытался узнать, как это делают другие, взглянув на подобный стек переполнение сообщений, однако мне как-то не удалось поднять asp идею о них. У меня была идея, что я мог бы использовать эту функцию для элемента, который имеет отсутствующие узлы, но, похоже, он не работал:

text_runtime<- webpage %>% 
      html_nodes(".NEGATIVE") %>% 
      html_text() %>% 
      {if(length(.) == 0) NA else .}

Эта функция также дает мне 43 элемента и не помещает никаких NA, где отсутствует узел.

1 Ответ

1 голос
/ 04 апреля 2020

Сначала вы должны извлечь .s-item__details, используя html_nodes, а из каждого узла извлечь .NEGATIVE или .s-item__hotness, используя html_node (без s).

library('rvest')

pages <- 1
page <- 0
output <- data.frame(header = character(), price = character(), runtime = character())
for (i in 1:pages) {

  page <- page + 1
  link <- paste("https://www.ebay.com/b/Cell-Phones-Smartphones/9355/bn_320094?LH_BIN=1&LH_ItemCondition=1000&rt=nc&_from=R40&_pgn=",page, sep="")

  webpage <- read_html(link)


  #read the name of the item
  header <- html_nodes(webpage, ".s-item__title")
  header_text <- html_text(header)

  #i get the price
  prim_html <- html_nodes(webpage, ".s-item__price")
  text_prim <- html_text(prim_html)

  price <- rbind(price,as.data.frame(text_prim))

  #i get the (amount sold this is missing sometimes)

  item <- html_nodes(webpage, ".s-item__details")
  runtime_html <- html_node(item, ".s-item__hotness")
  text_runtime <- html_text(runtime_html)
  text_runtime[is.na(text_runtime)] <- "0"

  # combine
  out <- data.frame(header_text, text_prim, text_runtime)
  output <- rbind(output, out)

  #prints 0 so i know that it went throught the for(){}
  print(0)

}

output

output

#                                                                                  header_text          text_prim text_runtime
# 1                      Google Nexus 5X H791 32GB (FACTORY UNLOCKED) 5.2" HD - Mint Green LG              $44.88      42 sold
# 2                 Motorola Moto Z3 Play 32GB - Unlocked - Deep Indigo - Brand New - XT1929-4            $177.02   7 watching
# 3                                 LG V20 -Brand New - H915 - Unlocked - Ships Express Canada            $162.16   5 watching
# 4           Samsung Galaxy J3 Unlocked 5" 16GB GSM 4G LTE Android Smartphone Black SM-J320W8             $77.89         0
# 5  New ListingSamsung Galaxy A30s SM-A307GN/DS Dual Sim (FACTORY UNLOCKED) 6.4" 64GB 4GB RAM            $212.43         0
# ...
# ...
# 42                Black phone 2 - 32GB - Black (Unlocked) Smartphone (Rest of World Version)            $318.65   5 watching
# 43                                                                               Sagem MC939            $199.00         0
# 44                                                                        Nokia 6220 classic            $199.00         0
# 45   New ListingSmart Mini Wireless HD Dual WiFi Pocket Projector 2G RAM 16G ROM Android 7.1            $353.35         0
# 46                                                                                nokia 7260            $149.25         0
# 47                                                                                smartphone            $250.00         0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...