使用SeleniumWebDriverJava单击动态加载页面的元素

使用SeleniumWebDriverJava单击动态加载页面的元素,java,javascript,selenium,selenium-webdriver,Java,Javascript,Selenium,Selenium Webdriver,我需要点击一个动态加载页面的特定元素。当我们滚动页面时生成的Web元素。它类似于jabong网页 我试着在jabong网页上这样做这是我的代码 WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.navigate().to("http://www.jabong.com/men/clothing/" + "?source=topnav"

我需要点击一个动态加载页面的特定元素。当我们滚动页面时生成的Web元素。它类似于jabong网页

我试着在jabong网页上这样做这是我的代码

    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.navigate().to("http://www.jabong.com/men/clothing/"
            + "?source=topnav");


    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    System.out.println("Close the modal popup");
    driver.findElement(By.id("jab-vchr-cls")).click();
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

      /**
       * while(true) loop is required to search the 
       * element until element found.We put find
       * element within try-catch and if it get 
       * exception it scroll the page and again 
       * try to find the element.
       */
    while(true) {

            ((JavascriptExecutor)driver).executeScript("window.scrollBy(0,100)", "");
        try {
            WebElement element = driver.findElement(By.xpath("//*[@id='http:    //static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img"));
            Wait<WebDriver> wait_element=new WebDriverWait(driver, 10);
            wait_element.until(ExpectedConditions.elementToBeClickable(element));
            element.click();
            System.out.println("!!!!!!!!!!!!!!At Last Get Success!!!!!!!!!!!!!!!!");
            break;

        }
        catch (Exception ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getMessage());
        }
        }
WebDriver=newfirefoxdriver();
driver.manage().window().maximize();
驱动程序。导航()。到(“http://www.jabong.com/men/clothing/"
+“?来源=topnav”);
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
System.out.println(“关闭模式弹出窗口”);
driver.findElement(By.id(“jab vchr cls”)。单击();
driver.manage().timeouts().implicitlyWait(0,TimeUnit.SECONDS);
/**
*while(true)循环是搜索
*元素,直到找到元素。我们将查找
*元素中的try-catch和if-get
*例外情况是,它会滚动页面并再次显示
*尝试查找元素。
*/
while(true){
((JavascriptExecutor)driver.executeScript(“window.scrollBy(0100)”,”);
试一试{
WebElement=driver.findelelement(By.xpath(“/*[@id='http://static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img”);
Wait Wait_元素=新的WebDriverWait(驱动程序,10);
wait_element.until(ExpectedConditions.element可禁用(element));
元素。单击();
System.out.println(“!!!!!!!!!!!!!!!!!!!!!最终获得成功!!!!!!!”;
打破
}
捕获(例外情况除外){
Logger.getLogger(Test.class.getName()).log(Level.SEVERE,null,ex);
System.out.println(例如getMessage());
}
}
} }

我的问题是

1.有没有更好的方法来做这件事

2.如何使此脚本更快

  • 在这个框架中,
    AutomationTest#waitForElement
    方法是处理事情的好方法。它是webdriver wait的替代品,但仍然可以工作

    /**
     * Private method that acts as an arbiter of implicit timeouts of sorts.. sort of like a Wait For Ajax method.
     */
    private WebElement waitForElement(By by) {
        int attempts = 0;
        int size = driver.findElements(by).size();
    
        while (size == 0) {
            size = driver.findElements(by).size();
            if (attempts == MAX_ATTEMPTS) fail(String.format("Could not find %s after %d seconds",
                                                             by.toString(),
                                                             MAX_ATTEMPTS));
            attempts++;
            try {
                Thread.sleep(1000); // sleep for 1 second.
            } catch (Exception x) {
                fail("Failed due to an exception during Thread.sleep!");
                x.printStackTrace();
            }
        }
    
        if (size > 1) System.err.println("WARN: There are more than 1 " + by.toString() + " 's!");
    
        return driver.findElement(by);
    }
    
  • 你可以把它从无限循环中取出来。如果一个页面在10秒内没有加载内容,我会说这是一个应用程序问题,需要纠正。将它从无限循环中取出,使用上面指定的
    waitForElement
    之类的东西,或者只使用
    WebDriverWait


  • 此外,您不应该滚动到某个元素。我还没有找到这样做的理由。只要元素在DOM上,就应该能够对其进行操作。

    如果希望避免while(true),可以这样做,尽管我认为这个循环没有任何问题

        boolean reachedbottom = Boolean.parseBoolean(js.executeScript("return $(document).height() == ($(window).height() + $(window).scrollTop());").toString());
    
        while (!reachedbottom) {
            ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,600)", "");
            try {
                reachedbottom=Boolean.parseBoolean(js.executeScript("return $(document).height() == ($(window).height() + $(window).scrollTop());").toString());
                WebElement element = driver.findElement(By.xpath("//*[@id='http://static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img"));
                Wait<WebDriver> wait_element = new WebDriverWait(driver, 5);
                wait_element.until(ExpectedConditions.elementToBeClickable(element));
                element.click();
                System.out.println("!!!!!!!!!!!!!!At Last Get Success!!!!!!!!!!!!!!!!");
                break;
            } catch (Exception ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            }
        }
    
    boolean-reachedbooth=boolean.parseBoolean(js.executeScript(“return$(document.height()==($(window.height()+$(window.scrollTop());”).toString());
    当(!到达底部){
    ((JavascriptExecutor)driver.executeScript(“window.scrollBy(0600)”,”);
    试一试{
    reachedbooth=Boolean.parseBoolean(js.executeScript(“return$(document.height()==($(window.height()+$(window.scrollTop());”).toString());
    WebElement=driver.findElement(By.xpath(“/*[@id='1])http://static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg“]/img”);
    Wait Wait_元素=新的WebDriverWait(驱动程序,5);
    wait_element.until(ExpectedConditions.element可禁用(element));
    元素。单击();
    System.out.println(“!!!!!!!!!!!!!!!!!!!!!最终获得成功!!!!!!!”;
    打破
    }捕获(例外情况除外){
    Logger.getLogger(Test.class.getName()).log(Level.SEVERE,null,ex);
    System.out.println(例如getMessage());
    }
    }
    
    当然有更好的方法可以做到这一点。。你永远不应该对这样的东西使用无限循环。@sircapsalot谢谢你的回复,我认为这是一个循环,但我没有找到任何其他方法来滚动页面并加载元素以找到所需的元素。因此,当找到所需的元素时,我使用break来停止这个循环。你有更好的主意吗?谢谢你的友好回复有用的代码。1.我想知道这是否真的是应用程序问题,因为如果网络速度慢?2.实际上页面向下滚动时会加载6000个或更多的元素,这是根据延迟加载特性。所以我需要实现这个循环。你想说如果我不实现这个循环并找到元素,它可以找到元素吗?事实上,我在这方面是新手,所以这可能是一些幼稚的问题。@sircapsalot while(true)。。。。。。break和while(size==0),因为这两件事做的是相同的工作。另一件事我想提到的是,如果元素没有找到,那么它会异常,而不会得到大小。不,但是如果你仔细观察循环,它只会尝试一定的次数。无论
    MAX\u尝试多少次
    都设置为。通常是5。所以从技术上讲,这只需要5秒。做与WebDriverWait完全相同的事情。直到(出现(某物),5)[伪代码]