rvest返回字符串而不是列表

问题描述 投票:0回答:1

根据documentation,来自html_nodes()rvest应该返回(引用)当应用于节点列表时,html_nodes()返回所有节点,将结果折叠到新的节点列表中。

因此,在我的情况下,它返回一个字符串,其中每个节点都被折叠。为何如此行为?通过调试,我无法在这种意义上得到任何改变。它总是返回相同的字符串,其中页码折叠:

123456789101112131415...4950

library(tidyverse)  
library(rvest)    
library(stringr)   
library(rebus)     
library(lubridate)

url <-'https://footballdatabase.com/ranking/world/1'
html <read_html(url)

get_last_page <- function(html){
  pages_data <- html %>% 
    # The '.' indicates the class
    html_nodes('.pagination') %>% 
    # Extract the raw text as a list
    html_text()                   
  # The second to last of the buttons is the one
  pages_data[(length(pages_data)-1)] %>%            

    unname() %>%                                     
    # Convert to number
    as.numeric()                                     
}

我还尝试用list()登记输出,没有财富。 html_node()也没有解决问题。

html r rvest
1个回答
1
投票

使用选择器'.pagination'只提取了一个节点,因此当应用html_text()时,该节点中的所有文本都会折叠在一起。更改CSS选择器以包含锚点然后提取文本,以便分别为每个节点返回一个向量。

html %>%
  html_nodes('.pagination a') %>%
  html_text()

 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "30" "31" "32"
[33] "33" "34" "35" "36" "37" "38" "39" "40" "41" "42" "43" "44" "45" "46" "47" "48" "49" "50"
© www.soinside.com 2019 - 2024. All rights reserved.