使用phantomJs Selenium滚动

时间:2015-05-26 11:26:05

标签: java selenium selenium-webdriver phantomjs

我正在尝试运行此特定代码来滚动网页,这是一种分页。它就像Firefox驱动程序的魅力一样,但是当我使用phantomJS时它不起作用并进入无限循环

public class Drivers {

public WebDriver phJS()
{
    File phantomjs = Phanbedder.unpack(); //Phanbedder to the rescue!

    String[] phantomArgs = new  String[] {
        "--webdriver-loglevel=NONE"
    };

    DesiredCapabilities dcaps = new DesiredCapabilities();
    dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomjs.getAbsolutePath());

    dcaps.setCapability( "phantomjs.cli.args", phantomArgs);
    WebDriver driver = new PhantomJSDriver(dcaps);
    phantomjs.delete();
    return driver;

}
public static void main(String args[]) throws IOException
{

    WebDriver wd=new FirefoxDriver();// Does Not work with new Drivers().phJS()

    wd.get("http://www.snapdeal.com/products/mobiles-mobile-phones/filters/Form_s~Smartphones#plrty|Brand:HTC|Ram_s:1%20GB^ 2%20GB^ 3%20GB^ 512%20MB%20and%20Below|Form_s:Smartphones|");
    wd= new PageScroll().scrollToBottom(wd);
    List<WebElement> wele = wd.findElements(By.xpath("//*[@class=' product-image ']/a"));
    for(WebElement we:wele)
    {
         System.out.println(we.getAttribute("href"));
    }
     wd.quit();
}

}

以下是执行滚动的代码

public class PageScroll {
WebDriver driver;
 public WebDriver scrollToBottom(WebDriver driver) {
     String oldpage="";
     String newpage="";
     do{
         oldpage=driver.getPageSource();
        ((JavascriptExecutor) driver)
                .executeScript("window.scrollTo(0, document.body.scrollHeight)");

         newpage=driver.getPageSource();
        System.out.println(oldpage.equals(newpage));
     }while(!oldpage.equals(newpage));
        return driver;
    }

}

当我使用PhantomJS时,它会进入无限循环,而我不明白为什么。是因为ajax脚本没有被执行?但如果是这样它应该走出循环,如果它滚动为什么它不像firefox驱动程序那样停止?

2 个答案:

答案 0 :(得分:1)

得到了答案,我打电话给了明确的等待。它工作正常

public synchronized WebDriver scrollToBottom(WebDriver driver, WebElement element,int time) throws InterruptedException {
     String oldpage="";
     String newpage="";


     do{
         oldpage=driver.getPageSource();
         ((JavascriptExecutor) driver)
                .executeScript("window.scrollTo(0, (document.body.scrollHeight))");
         this.wait(time);
         newpage=driver.getPageSource();
    }while(!oldpage.equals(newpage));
        return driver;
    }

答案 1 :(得分:0)

当您滚动到底部时,LinkedIn正在更改页面,请求更多数据。这意味着滚动后你永远不会得到相同的结果。

我不确定你为什么在Firefox中看不到;也许它会在您调用getPageSource()getPageSource()返回陈旧数据后处理滚动事件。

相关问题