【问题标题】:How to scrape specific information from website with several pages in R如何在 R 中使用多个页面从网站上抓取特定信息
【发布时间】:2020-12-05 14:13:41
【问题描述】:
【问题讨论】:
标签:
r
function
web-scraping
【解决方案1】:
这是一种使用 rvest 的方法。请记住,特定网站(hot100)实际上并不使用分页,因此 url 的 ?page=1 等部分没有意义(它只是不断加载主页)。但是对于 分页的网站,这会起作用
library(tidyverse)
library(rvest)
hot100page <- "https://www.billboard.com/charts/hot-100"
hot100 <- read_html(hot100page)
df <- data.frame(rank=character(), somethingelse=character())
rank <- c()
for(i in 1:32) {
print(paste0("Scraping page ", i))
temp <- paste0(hot100page, '?page=', i) %>%
read_html %>%
rvest::html_nodes('body') %>%
xml2::xml_find_all("//span[contains(@class, 'chart-element__rank__number')]") %>%
rvest::html_text()
rank <- c(rank, temp)
}
df$rank <- rank
df
【解决方案2】:
我建议你使用RSelenium。
以下可能的解决方案。
#Start the library
library(RSelenium)
#Start a selenium server and browser (you have to select it)
driver <- rsDriver(browser=c("firefox"), port = 4567L)
#Defines the client part.
remote_driver <- driver[["client"]]
#Sent the web site address to the firefox
remote_driver$navigate("https://www.amazon.com/s?k=statistics&ref=nb_sb_noss_2.")
#a empty list to save the data
all_books<-list()
#a loop to click next
for (i in 1:20) {
#sleeps to wait that the page is available
Sys.sleep(3)
#finds in the css environment the body
scroll_d <- remote_driver$findElement(using = "css", value = "body")
#sends to the browser to go to the end of the page
scroll_d$sendKeysToElement(list(key = "end"))
#gets all books, price, ranking, etc
all_books[i]<-remote_driver$findElement(using = 'css selector', value = 'span.s-latency-cf-section:nth-child(4)')$getElementText()
#pushes the button next
next_bottom<-remote_driver$findElement(using = 'css selector',value = '.a-last')
next_bottom$clickElement()
}
head(all_books)
[[1]]
[1] "1\nNew\nLife Goes On\nBTS\n-\n1\n1\n2\nFailing\nMood\n24kGoldn Featuring iann dior