How to return NA when nothing is found in an xpath?

前端 未结 2 882
孤独总比滥情好
孤独总比滥情好 2021-01-28 22:33

It is difficult to formulate the question, but with an example, it is simple to understand.

I use R to parse html code.

In the following, I have a html code call

2条回答
  •  臣服心动
    2021-01-28 23:01

    It's easier to select the enclosing tag (the div here) for each, and look for each tag inside. With rvest and purrr, which I find simpler,

    library(rvest)
    library(purrr)
    
    html %>% read_html() %>% 
        html_nodes('.line') %>% 
        map_df(~list(number = .x %>% html_node('.number') %>% html_text(), 
                     surface = .x %>% html_node('.surface') %>% html_text()))
    
    #> # A tibble: 2 × 2
    #>     number   surface
    #>           
    #> 1 Number 1 Surface 1
    #> 2      Surface 2
    

提交回复
热议问题