2017-03-04 68 views
1

我不確定是否因爲我的網絡速度很慢,但我試圖抓取一個網站,在向下滾動頁面時加載信息。我正在執行一個到頁面末尾的腳本,並等待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 

回答

0

該網站提供了一個api這應該是第一個通話端口。如果做不到這一點,你可以使用例如訪問個人網頁:

http://www.codewars.com/kata?page=21 

如果要滾動到頁面的底部,直到有沒有更多的內容與RSelenium您可以使用「載入中...」元素,它具有一個class=js-infinite-marker。雖然我們仍然在頁面上有這個元素,但我們仍然試圖每秒向下滾動(有些問題會引發任何問題)。如果元素不存在,我們假設所有內容都已加載:

library(RSelenium) 

rD <- rsDriver(port = 4444L, browser = 'chrome') 
remDr <- rD$client # You dont need to use the open method 
remDr$navigate('http://www.codewars.com/kata') 
chk <- FALSE 
while(!chk){ 
    webElem <- remDr$findElements("css", ".js-infinite-marker") 
    if(length(webElem) > 0L){ 
    tryCatch(
     remDr$executeScript("elem = arguments[0]; 
         elem.scrollIntoView(); 
         return true;", list(webElem[[1]])), 
     error = function(e){} 
    ) 
    Sys.sleep(1L) 
    }else{ 
    chk <- TRUE 
    } 
}