我正在努力在網頁上完成抓取。我的任務是從網站上抓取評論并對其進行情緒分析。但是我只設法在第一頁上完成了抓取,我怎樣才能抓取分布在多個頁面上的同一部電影的所有評論。
這是我的代碼:
library(rvest)
read_html("https://www.rottentomatoes.com/m/dune_2021/reviews") %>%
html_elements(xpath = "//div[@class='the_review']") %>%
html_text2()
這只會讓我獲得第一頁的評論,但我需要所有頁面的評論。任何幫助將不勝感激。
uj5u.com熱心網友回復:
您可以避免瀏覽器的昂貴開銷并使用 httr2。該頁面使用 queryString GET 請求批量抓取評論。對于每個批次,startCursor 和 endCursor 的偏移引數可以從之前的請求中獲取,并且有一個 hasNextPage 標志欄位可以用來終止額外評論的請求。初始請求需要獲取title id,offset引數可以設定為''。
在收集了所有評論后,在我的例子中,我應用了一個自定義函式來從每個評論中提取一些可能感興趣的專案,以生成最終的資料框。
致謝:我repeat()從@flodal 那里得到了使用的想法
library(tidyverse)
library(httr2)
get_reviews <- function(results, n) {
r <- request("https://www.rottentomatoes.com/m/dune_2021/reviews") %>%
req_headers("user-agent" = "mozilla/5.0") %>%
req_perform() %>%
resp_body_html() %>%
toString()
title_id <- str_match(r, '"titleId":"(.*?)"')[, 2]
start_cursor <- ""
end_cursor <- ""
repeat {
r <- request(sprintf("https://www.rottentomatoes.com/napi/movie/%s/criticsReviews/all/:sort", title_id)) %>%
req_url_query(f = "", direction = "next", endCursor = end_cursor, startCursor = start_cursor) %>%
req_perform() %>%
resp_body_json()
results[[n]] <- r$reviews
nextPage <- r$pageInfo$hasNextPage
if (!nextPage) break
start_cursor <- r$pageInfo$startCursor
end_cursor <- r$pageInfo$endCursor
n <- n 1
}
return(results)
}
n <- 1
results <- list()
data <- get_reviews(results, n)
df <- purrr::map_dfr(data %>% unlist(recursive = F), ~
data.frame(
date = .x$creationDate,
reviewer = .x$publication$name,
url = .x$reviewUrl,
quote = .x$quote,
score = if (is.null(.x$scoreOri)) {
NA_character_
} else {
.x$scoreOri
},
sentiment = .x$scoreSentiment
))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483221.html
