我不確定是否因爲我的網絡速度很慢,但我試圖抓取一個網站,在向下滾動頁面時加載信息。我正在執行一個到頁面末尾的腳本,並等待Selenium/Chrome服務器加載額外的內容。服務器確實會更新並加載新內容,因爲我能夠抓取最初不在頁面上的信息,並且新內容在Chrome瀏覽器中顯示,但它只更新一次。我設置了一個Sys.sleep()
函數,每次等待一分鐘,以便內容有足夠的時間加載,但它仍不會更新多次。我錯誤地使用RSelenium?是否有其他方式來刮取動態加載的網站?RSelenium:刮動載入緩慢的動態加載頁面
無論如何,任何類型的建議或幫助,你可以提供將是非常棒的。
下面是我認爲是我的代碼考慮到負載在頁面末尾的新內容的相關部分:
for(i in 1:3){
webElem <- remDr$findElement('css', 'body')
remDr$executeScript('window.scrollTo(0, document.body.scrollHeight);')
Sys.sleep(60)
}
以下是完整代碼:
library(RSelenium)
library(rvest)
library(stringr)
rsDriver(port = 4444L, browser = 'chrome')
remDr <- remoteDriver(browser = 'chrome')
remDr$open()
remDr$navigate('http://www.codewars.com/kata')
#find the total number of recorded katas
tot_kata <- remDr$findElement(using = 'css', '.is-gray-text')$getElementText() %>%
unlist() %>%
str_extract('\\d+') %>%
as.numeric()
#there are about 30 katas per page reload
tot_pages <- (tot_kata/30) %>%
ceiling()
#will be 1:tot_pages once I know the below code works
for(i in 1:3){
webElem <- remDr$findElement('css', 'body')
remDr$executeScript('window.scrollTo(0, document.body.scrollHeight);')
Sys.sleep(60)
}
page_source <- remDr$getPageSource()
kata_vector <- read_html(page_source[[1]]) %>%
html_nodes('.item-title a') %>%
html_attr('href') %>%
str_replace('/kata/', '')
remDr$close