使用Selenium WebDriver java单击动态加载页面的元素

时间:2022-03-02 16:00:16

I need to click on particular element of an dynamically loaded page.Web element generated when we scroll the page.It similar like an jabong webpage.

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

I try to do that on jabong webpage this is my code

我试着在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());
        }
        }

} }

}}

My question is

我的问题是

1.Is there any better way to do this things?

1.有没有更好的办法做这件事?

2.How to make this script faster?

2.如何让这个脚本更快?

2 个解决方案

#1


2  

you can do this way if you want to avoid while(true) though I donot think there is any problem with this loop.

你可以这样做,如果你想避免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());
        }
    }

#2


0  

  1. In the Getting Started with Selenium framework, the AutomationTest#waitForElement method is a great way to handle things. It's an alternative to the webdriver wait, but works all the same.

    在Selenium入门框架中,AutomationTest#waitForElement方法是处理事物的好方法。它是webdriver等待的替代品,但工作原理完全相同。

    /**
     * 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);
    }
    
  2. You can take it out of the infinite loop. If a page doesn't load something within 10 seconds then i'd say it's an app issue that needs to be rectified. Take it out out of the infinite loop, and using something like waitForElement specified above, or just use a WebDriverWait class.

    你可以把它从无限循环中取出来。如果页面在10秒内没有加载某些东西,那么我会说这是一个需要纠正的应用程序问题。将它从无限循环中取出,并使用上面指定的waitForElement,或者只使用WebDriverWait类。

Furthermore, you shouldn't ever have to scroll to an element. I still have yet to find a reason to do something like this. As long as the element is on the DOM, it should be able to be operated on.

此外,您不必滚动到元素。我还没有找到做这样事情的理由。只要元素在DOM上,它就应该能够被操作。

#1


2  

you can do this way if you want to avoid while(true) though I donot think there is any problem with this loop.

你可以这样做,如果你想避免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());
        }
    }

#2


0  

  1. In the Getting Started with Selenium framework, the AutomationTest#waitForElement method is a great way to handle things. It's an alternative to the webdriver wait, but works all the same.

    在Selenium入门框架中,AutomationTest#waitForElement方法是处理事物的好方法。它是webdriver等待的替代品,但工作原理完全相同。

    /**
     * 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);
    }
    
  2. You can take it out of the infinite loop. If a page doesn't load something within 10 seconds then i'd say it's an app issue that needs to be rectified. Take it out out of the infinite loop, and using something like waitForElement specified above, or just use a WebDriverWait class.

    你可以把它从无限循环中取出来。如果页面在10秒内没有加载某些东西,那么我会说这是一个需要纠正的应用程序问题。将它从无限循环中取出,并使用上面指定的waitForElement,或者只使用WebDriverWait类。

Furthermore, you shouldn't ever have to scroll to an element. I still have yet to find a reason to do something like this. As long as the element is on the DOM, it should be able to be operated on.

此外,您不必滚动到元素。我还没有找到做这样事情的理由。只要元素在DOM上,它就应该能够被操作。