首页 > 解决方案 > 在网络抓取中找不到网站的页数

问题描述

我想从网站上获取页面数。我尝试像在教程中那样做。我使用了这个功能:

get_last_page <- function(html){

  pages_data <- html %>% 
                  # The '.' indicates the class
                  html_nodes('.pagination-page') %>% 
                  # 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)] %>%            
    # Take the raw string
    unname() %>%                                     
    # Convert to number
    as.numeric()                                     
}
first_page <- read_html(url)
(latest_page_number <- get_last_page(first_page))

用于网站

url <-'http://www.trustpilot.com/review/www.amazon.com'

它工作正常。当我尝试这样做时

url <-'https://energybase.ru/en/oil-gas-field/index'

我得到整数(0)。

我改变

html_nodes('.pagination-page') 

html_nodes('.html_nodes('data-page')') 

并且失败了。如何更改我的代码以使其正常工作?

标签: htmlrweb-scraping

解决方案


我认为你必须在这里采取一些不同的方式。

energybase.ru URL的组织方式与 TrustPilot URL不同。

出于我们的目的,我们对最后一页有自己的节点这一事实感兴趣.last。从那里,您只需提取data-page属性的值并将其增加 1。

library("rvest") 
library("magrittr")

url <- 'https://energybase.ru/en/oil-gas-field/index'

read_html(url) %>% html_nodes(".last") %>% html_children() %>% html_attr("data-page") %>% as.numeric()+1
# [1] 21

编辑:请注意,您始终可以在html_children()(通过添加 a %>% html_attrs())截取管道以找出您可以使用的属性。


推荐阅读