我想在最近的一次会议上使用rvest来抓取一个有头衔和会话时间的页面,然后将这些值组合成一个单词
library(tibble)
library(rvest)
url <- "https://channel9.msdn.com/Events/useR-international-R-User-conferences/useR-International-R-User-2017-Conference?sort=status&direction=desc&page=14"
title <- page %>%
html_nodes("h3 a") %>%
html_text()
length <- page %>%
html_nodes(".tile .caption") %>%
html_text()
df <- tibble(title,length)
如果您查看该页面,您会看到其中一个会话没有任何价值 - 而在View源中,此话题没有class="caption"
我有什么方法可以替换NA
来显示缺失值吗?
答案 0 :(得分:0)
最简单的方法是选择一个节点,该节点包含每行所需的两个节点,然后迭代它们,同时拉出所需的两个节点。 purrr::map_df
不仅可以迭代,还可以将结果组合成一个漂亮的元素:
library(rvest)
library(purrr)
url <- "https://channel9.msdn.com/Events/useR-international-R-User-conferences/useR-International-R-User-2017-Conference?sort=status&direction=desc&page=14"
page <- read_html(url)
df <- page %>%
html_nodes('article') %>% # select enclosing nodes
# iterate over each, pulling out desired parts and coerce to data.frame
map_df(~list(title = html_nodes(.x, 'h3 a') %>%
html_text() %>%
{if(length(.) == 0) NA else .}, # replace length-0 elements with NA
length = html_nodes(.x, '.tile .caption') %>%
html_text() %>%
{if(length(.) == 0) NA else .}))
df
#> # A tibble: 12 x 2
#> title length
#> <chr> <chr>
#> 1 Introduction to Natural Language Processing with R II 01:15:00
#> 2 Introduction to Natural Language Processing with R 01:22:13
#> 3 Solving iteration problems with purrr II 01:22:49
#> 4 Solving iteration problems with purrr 01:32:23
#> 5 Markov-Switching GARCH Models in R: The MSGARCH Package 15:55
#> 6 Interactive bullwhip effect exploration using SCperf and Shiny 16:02
#> 7 Actuarial and statistical aspects of reinsurance in R 14:15
#> 8 Transformation Forests 16:19
#> 9 Room 2.02 Lightning Talks 50:35
#> 10 R and Haskell: Combining the best of two worlds 14:45
#> 11 *GNU R* on a Programmable Logic Controller (PLC) in an Embedded-Linux Environment <NA>
#> 12 Performance Benchmarking of the R Programming Environment on Knight's Landing 19:32
答案 1 :(得分:0)
我遇到了同样的问题,但是我设法使其工作而没有涉及包围两个指定节点的节点。
使用您的代码将是:
library(tibble)
library(rvest)
url <- "https://channel9.msdn.com/Events/useR-international-R-User-conferences/useR-International-R-User-2017-Conference?sort=status&direction=desc&page=14"
title <- page %>%
html_nodes("h3 a") %>%
html_text() %>%
{if(length(.) == 0) NA else .
length <- page %>%
html_nodes(".tile .caption") %>%
html_text() %>%
{if(length(.) == 0) NA else .
df <- tibble(title,length)