【发布时间】:2020-04-04 05:59:10
【问题描述】:
大家好!
很长一段时间以来,我一直在尝试抓取数据并以某种方式将丢失的 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)
}
附注我知道它看起来很糟糕,但我每天都在学习如何更好地编码。
代码输出 48 obs 的价格和产品名称,但是,当涉及到已售或剩余的数量时,它给了我 43。
我试图通过查看类似的堆栈overflow帖子来了解其他人是如何做到的,但是,我不知何故未能掌握他们的想法。 我的想法是,我可以将此函数用于缺少节点的元素,但它似乎不起作用:
text_runtime<- webpage %>%
html_nodes(".NEGATIVE") %>%
html_text() %>%
{if(length(.) == 0) NA else .}
这个函数也给了我 43 个元素,并且没有在节点丢失的地方放置任何 NA。
【问题讨论】: