首页 > 解决方案 > 我正在尝试抓取多个页面

问题描述

我正在尝试从游戏网站的同一网站上抓取多个页面以进行评论。

我尝试运行它并更改我在这里找到的代码:R web scraping across multiple pages with the answer之一。

library(tidyverse)
library(rvest)

url_base <- "https://www.metacritic.com/browse/games/score/metascore/all/ps4?sort=desc&page=0"

map_df(1:17, function(i) {


  cat(".")

 pg <- read_html(sprintf(url_base, i))

data.frame(Name = html_text(html_nodes(pg,"#main .product_title a")),
         MetaRating = as.numeric(html_text(html_nodes(pg,"#main .positive"))),
         UserRating = as.numeric(html_text(html_nodes(pg,"#main .textscore"))),
         stringsAsFactors = FALSE)

}) -> ps4games_metacritic

结果是第一页被刮了 17 次,而不是网站上的 17 页

标签: rrvest

解决方案


我对您的代码进行了三处更改:

  1. 因为他们的页码从 0 开始,map_df(1:17... 应该是map_df(0:16...
  2. 正如 BigDataScientist 所提议的, url_base应该这样设置:url_base <- "https://www.metacritic.com/browse/games/score/metascore/all/ps4?sort=desc&page=%d"
  3. 如果你使用"#main .positive"你会在 抓取第 7 页时出错,因为没有正面分数的游戏从那里开始 - 除非你只想抓取具有正面评价的游戏(这意味着代码有点不同),你应该 "#main .game"改用
    library(tidyverse)
    library(rvest)
    
    url_base <- "https://www.metacritic.com/browse/games/score/metascore/all/ps4?sort=desc&page=%d"
    
    map_df(0:16, function(i) {
      
      
      cat(".")
      pg <- read_html(sprintf(url_base, i))
    
      data.frame(Name = html_text(html_nodes(pg,"#main .product_title a")),
                 MetaRating = as.numeric(html_text(html_nodes(pg,"#main .game"))),
                 UserRating = as.numeric(html_text(html_nodes(pg,"#main .textscore"))),
                 stringsAsFactors = FALSE)
      
    }) -> ps4games_metacritic

推荐阅读