首页 > 解决方案 > rvest 返回字符串而不是列表

问题描述

根据文档html_nodes()fromrvest应该返回(引用) 当应用于节点列表时, 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()没有解决问题。

标签: htmlrrvest

解决方案


选择器“.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"

推荐阅读