首页 > 解决方案 > 使用 RSelenium 滚动到长动态页面的末尾

问题描述

我想出了如何使用 RSelenium 滚动动态页面,但是页面的长度每次都不同,所以有时对于包含许多元素的长页面,我的代码不起作用,它在到达页面底部之前就停止了。有人知道如何避免它吗?先感谢您!

我的代码示例:第一个效果很好,让它以这种方式滚动到页面末尾可能会很棒。我不应该以某种方式定义像 10 这样的特定卷轴数量,而是分配条件以重复这种卷轴直到特定时刻。但是不知道怎么...

    for(i in 1:10){ 
  cd$executeScript(paste("scroll(0,",i*10000,");"))
  Sys.sleep(3)    
}

###after 10 big scrolls starts mini scrolls like that###
element <- cd$findElement("css", "body")
flag <- TRUE
counter <- 0
n <- 5
while(flag){
  counter <- counter + 1
  #compare the pagesource every n(n=5) time, since sometimes one scroll down doesn't render new content
  for(i in 1:n){
    element$sendKeysToElement(list("key"="page_down"))
    Sys.sleep(2)
  }
  if(exists("pagesource")){
    if(pagesource == cd$getPageSource()[[1]]){
      flag <- FALSE
      writeLines(paste0("Scrolled down ",n*counter," times.\n"))
    } else {
      pagesource <- cd$getPageSource()[[1]]
    }
  } else {
    pagesource <- cd$getPageSource()[[1]]
  }
} #But unfortunately this line is also powerless before the real big pages so it stops before reaching the bottom

标签: rparsingscrollrselenium

解决方案


推荐阅读