r - 我正在尝试抓取多个页面
问题描述
我正在尝试从游戏网站的同一网站上抓取多个页面以进行评论。
我尝试运行它并更改我在这里找到的代码: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 页
解决方案
我对您的代码进行了三处更改:
- 因为他们的页码从 0 开始,
map_df(1:17...
应该是map_df(0:16...
- 正如 BigDataScientist 所提议的,
url_base
应该这样设置:url_base <- "https://www.metacritic.com/browse/games/score/metascore/all/ps4?sort=desc&page=%d"
- 如果你使用
"#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
推荐阅读
- javascript - Firestore 离线似乎无法正常工作
- python - 随机生成的迷宫
- python - 根据条件选择数据框列
- database - 在数据库中使用 `@SequenceGenerator` 与自动增量相比有什么优势?
- javascript - JS:获取数字后的子字符串
- asp.net - 如何避免 VB ASP GridView 中的重复?
- node.js - 检查数组中是否存在对象,如果存在则在nodejs mongoose中设置状态为真
- python - 在 Python 中查找两个时间字符串之间的差异
- git - GIT:如果我推送一个不是当前分支的分支会发生什么?
- ios - 选择器函数未在 iOS Swift 中调用