2015-10-13 21 views
9

Selenio:Selenio: Scorrere fino alla fine della pagina

Sono nuovo di WebDriverJS. Ho provato questo approccio in Java.

Long repaeted = 0l, scrollHeight = 0l, returnHeight = 0l; 
while(true){ 
    if (repaeted == 0) { 
     returnHeight = (Long) jse.executeScript("var scroll =document.documentElement.scrollHeight;window.scrollTo(0, scroll); return scroll;"); 
     System.out.println("Height : "+scrollHeight +"\t Chnage : "+returnHeight+ "\t Repeated : "+repaeted); 
     scrollHeight = returnHeight; 
    }else { 
     returnHeight = (Long) jse.executeScript("var scroll = document.documentElement.scrollHeight;window.scrollTo(0, scroll); return scroll;"); 
     System.out.println("Height : "+scrollHeight +"\t Chnage : "+returnHeight+ "\t Repeated : "+repaeted); 
     if (scrollHeight.intValue() == returnHeight.intValue()) { 
      System.out.println("Break.."+ returnHeight); 
      break; 
     } else { scrollHeight = returnHeight; } 
    } 
      repaeted++; 
} 

ma sto affrontando problema in webdriverjs mentre l'iterazione del ciclo.

var webdriver = require('..'), 
    By = webdriver.By, 
    until = webdriver.until; 
// make sure chromedriver can be found on your system PATH 
var driver = new webdriver.Builder() 
    .forBrowser('chrome') 
    .withCapabilities(webdriver.Capabilities.chrome()) 
    .build(); 


driver.get('https://in.yahoo.com/').then(function(){ 
     var window = new webdriver.WebDriver.Window(driver); 
     window.maximize(); 
     driver.manage().timeouts().implicitlyWait(1000 * 3); 
    }) 
    .then(function(){ 
     console.log('Entered'); 
     var check = 0, count = 0 
     for(var i = 0; i< 50; i++){ 
     //driver.sleep(1000 * 2); 
driver.executeScript('var dynamicscroll = document.documentElement.scrollHeight;window.scrollTo(0, dynamicscroll);return dynamicscroll;').then(function(height){ 
     console.log('Check : '+check+' Height : '+height +' Repeated : '+(count++)); 
     if(check === 0 || check !== height){console.log('continue'); check = height; } 
     else { console.log('break'); i = 100; } 
      }); 
     } 
     }) 
    .then(null, function(err) { 
     console.error("An error was thrown! By Promise..." + err); 
    }); 

driver.quit(); 

Nel mio codice ho hardcoded ciclo for per iterare fino a 50 volte e voglio uscire/rompere il ciclo quando si raggiunge l'altezza di scorrimento per finire. Con questo approccio, voglio rimuovere hardcode come java-code perché non so quante volte per iterare per altre applicazioni il cui scorrimento è tenuto ad aumentare dinamicamente. Per esempio, l'applicazione Facebook, Yahoo News ...

risposta

5

Scorrere alla fine di una pagina dinamica può essere difficile a seconda di come è implementato dalla pagina.

Prima devi trovare il contenitore con la barra di scorrimento poiché può essere diverso da quello collegato a window.scrollTo.

Quindi scorrere il contenitore aumentando scrollTop finché lo scrollHeight diventa stabile senza richieste in sospeso. Per verificare se ci sono richieste in sospeso, puoi valutare jQuery.active se la pagina ha JQuery o hook XMLHttpRequest per monitorare le chiamate su send.

Ecco un esempio di utilizzo su una funzione generica per scorrere fino alla parte inferiore della pagina di un certo numero di volte o fino alla fine:

var webdriver = require('selenium-webdriver'); 

var driver = new webdriver.Builder().forBrowser('chrome').build(); 

driver.get('https://groups.google.com/forum/#!search/webdriverjs'); 

// scroll to the bottom 3 times 
driver.executeAsyncScript(scrollBottom, 3) 
    .then(n => console.log(`scrolled ${n} time(s)`)); 

// scroll to the bottom until the end 
driver.executeAsyncScript(scrollBottom) 
    .then(n => console.log(`scrolled ${n} time(s)`)); 
function scrollBottom(){ 
    var count = arguments[arguments.length - 2] || 0x7fffffff; 
    var callback = arguments[arguments.length - 1]; 

    /* get the scrollable container */ 
    var elm = document.elementFromPoint(window.innerWidth - 25, window.innerHeight/2); 
    for (;elm && (++elm.scrollTop, !elm.scrollTop); elm=elm.parentElement); 
    elm = elm || document.documentElement; 

    /* hook XMLHttpRequest to monitor Ajax requests */ 
    if (!('idle' in XMLHttpRequest)) (function(){ 
    var n = 0, t = Date.now(), send = XMLHttpRequest.prototype.send; 
    var dispose = function(){ --n; t = Date.now(); }; 
    var loadend = function(){ setTimeout(dispose, 1) }; 
    XMLHttpRequest.idle = function() { return n > 0 ? 0 : Date.now() - t; }; 
    XMLHttpRequest.prototype.send = function(){ 
     ++n; 
     this.addEventListener('loadend', loadend); 
     send.apply(this, arguments); 
    }; 
    })(); 

    /* scroll until steady scrollHeight or count of scroll and no pending request */ 
    var i = 0, scrollHeight = -1, scrollTop = -1; 
    (function scroll(){ 
    if ((scrollHeight === elm.scrollHeight || i === count) && XMLHttpRequest.idle() > 60) 
     return callback(i); 
    scrollTop = elm.scrollTop; 
    scrollHeight = elm.scrollHeight; 
    if (i < count) 
     i += (elm.scrollTop = 0x7fffffff, scrollTop !== elm.scrollTop); 
    setTimeout(scroll, 100); 
    })(); 
} 

o scorrendo fino all'altezza non aumenta più durante un momento specifico (5 secondi qui):

function scrollBottom(){ 
    var count = arguments[arguments.length - 2] || 0x7fffffff; 
    var callback = arguments[arguments.length - 1]; 
    var timeout = 5000; /* 5 seconds timeout */ 
    var i = 0; 

    /* get the scrollable container */ 
    var elm = document.elementFromPoint(window.innerWidth - 25, window.innerHeight/2); 
    for (;elm && (++elm.scrollTop, !elm.scrollTop); elm=elm.parentElement); 
    elm = elm || document.documentElement; 

    /* scroll while the height is increasing or until timeout */ 
    (function scroll(){ 
    var endtime = Date.now() + timeout; 
    var height = elm.scrollHeight; 
    elm.scrollTop = 0x7fffffff; /* scroll */ 

    setTimeout(function check(){ 
     if (Date.now() > endtime)   /* returns if waited more than 5 sec */ 
     callback(i); 
     else if (elm.scrollHeight == height) /* wait again if same height */ 
     setTimeout(check, 60); 
     else if (++i === count)    /* returns if scrolled the expected count */ 
     callback(i); 
     else         /* scroll again */ 
     setTimeout(scroll, 60); 
    }, 250); 
    })(); 
} 
+0

Puoi verificare con questo URL: 'https: // in.yahoo.com /'. e la mia domanda è che voglio interrompere il ciclo quando raggiunge la fine usando 'webdriverjs.' quale URL hai selezionato contiene' div scroll'. – Yash

+0

@Yash, funziona con https://in.yahoo.com/. La tua domanda è come scorrere verso il basso fino alla fine di una pagina Web quando l'altezza di scorrimento aumenta dinamicamente, che è esattamente ciò che questo esempio fa con 'webdriverjs'. Ho aggiunto un altro esempio che scorre fino a quando l'altezza non aumenta più durante un tempo specifico. –

+0

Puoi verificare che il codice stia generando l'errore 'ScriptTimeoutError: timeout di script asincrono: il risultato non è stato ricevuto in 0 secondi ogni volta durante l'esecuzione. – Yash

1

Pure JavaScript:

In JavaScript è possibile utilizzare la funzione setTimeout(). che chiamerà la funzione specificata in modo ricorsivo dopo il ritardo specificato.

Ho testato l'applicazione Google Gruppi, il cui scorrimento verticale tag div aumenta dinamicamente. Per caricare il contenuto ho usato il tempo di ritardo di 5000. puoi testare questo codice nella console del browser usa questo URL: https://groups.google.com/forum/#!search/webdrierjs.

var i = 0, height = 0, check = 0, t = null; 
flow(); 

function run(arg){ 
var objDiv = document.querySelector('div.IVILX2C-b-F'); 
objDiv.scrollTop = objDiv.scrollHeight; 
return objDiv.scrollHeight; 
} 

function flow() { 
i++; 
    switch(i){ 
     case 0:  height = run(i); 
        sleep(5000); 
       break; 
     case -1: run(i); 
        clearTimeout(t); //stops flow 
       break; 
     default: check = run(i); 
        console.log('Return Height : '+check +' Count : '+i); 
        if(check === height){ i = -2; 
        console.log('Break message : '+i); 
        }else { 
        console.log('Changed...'); 
        height = check; 
        } 
       sleep(5000); 
       break; 
    } 
} 

function sleep(delay) { t=setTimeout("flow()",delay);} //starts flow control again after time specified. 
//function sleep(delay) { var start = new Date().getTime();  while (new Date().getTime() < start + delay); flow(); } // stops execution and then continues. 

ma anche io non riesco a eseguire questo script utilizza WebDriver/WebDriverJS perché non è intenzione di chiamare la funzione ricorsiva in ritardo.

+0

Questo codice genera un errore se utilizzato in modalità di conformità rigorosa ('t' è globale). –

+0

@ A Red Herring grazie): - ora ho cambiato t come variabile locale var t = null; e testato !. ora la 'i' sta aumentando correttamente. – Yash

0

per esperienza, il modo più rapido per scorrere fino alla fine di una pagina è quello di cercare l'elemento piè di pagina e movetoit, di solito #footer o .footer o solo il selettore footer lo farà. Per esempio.:

footer = driver.findElement({id: "footer"}); 
driver.executeScript("arguments[0].scrollIntoView(false);", footer); 

Nel caso dei corsi d'acqua 'infinite' come Facebook, Twitter, ecc Essi possono bloccare quando si raggiunge un limite quindi è bene combinare iterazioni max con window.scrollTo(0, 300); ricorsivamente e attendere alcuni secondi dopo ogni rotolo .

0

provare questo codice - il suo funzionamento in Python (basta tradurre nel tuo caso):

# Get scroll height. 
    last_height = self.driver.execute_script("return document.body.scrollHeight") 

    while True: 
     # Scroll down to the bottom. 
     self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") 

     # Wait to load a page. 
     time.sleep(2) 

     # Calculate new scroll height and compare with last scroll height. 
     new_height = self.driver.execute_script("return document.body.scrollHeight") 
     if new_height == last_height: 
      break 
     last_height = new_height 

BTW: Ecco io sono in esecuzione JavaScript da Python.

Problemi correlati