【问题标题】:Not able to select drop down list ,showing invisible无法选择下拉列表,显示不可见
【发布时间】:2017-05-28 11:36:00
【问题描述】:

以下代码无法选择“摊销”下拉菜单

   import java.awt.Toolkit;    
    import org.junit.Assert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.Dimension;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class PracticeTest {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        WebDriverWait wait;

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\dilu316\\Downloads\\selenium workspace\\chromedriver\\chromedriver.exe");

        //approach 1 - to maximize screen in chrome
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");;
        driver = new ChromeDriver(options);
        wait=new WebDriverWait(driver, 50);

        //if the below method wont work for maximizing screen then above method we can use
        //WebDriver driver = new ChromeDriver();
        //Thread.sleep(5000);
        //driver.manage().window().maximize();

        driver.get("http://ia.ca/");

        //approach 2 - to maximize screen in chrome
        /*Toolkit toolkit = Toolkit.getDefaultToolkit();
        int height = (int)toolkit.getScreenSize().getHeight();
        int width  = (int)toolkit.getScreenSize().getWidth();
        System.out.println(height + "--" + width);

        driver.manage().window().setSize(new Dimension(width, height));*/


        driver.findElement(By.xpath("//*[@id='nav-secondaire']//a[@data-utag-name='loans']")).click();
        driver.findElement(By.xpath("//a[contains(text(),'Mortgages')]")).click();
        //in the upper xpath we can put a ". in place of text()" also

        //method 1 -if element is not clickable
        /*WebDriverWait wait = new WebDriverWait(driver, 100);
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Calculate your payments')]")));*/

        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("scroll(255, 644)");
        driver.findElement(By.xpath("//a[contains(.,'Calculate your payments')]")).click();

        WebElement priceSlideLocator = driver.findElement(By.xpath("//div[@class='slider-handle min-slider-handle custom']"));
        WebElement slideTrack = driver.findElement(By.xpath("//div[@class='slider-track-high']"));
        Dimension sliderSize = slideTrack.getSize();
        int sliderWidth = sliderSize.getWidth();
        int xCoord = priceSlideLocator.getLocation().getX();
        System.out.println(xCoord);
        System.out.println(sliderWidth);
        Thread.sleep(10);
        Actions builder = new Actions(driver);
        builder.moveToElement(priceSlideLocator)
        .click()
        .dragAndDropBy(priceSlideLocator, xCoord+sliderWidth,0)
        .build()
        .perform();

        WebElement hiddenPriceLocator = driver.findElement(By.xpath("//input[@id='sliderPrixPropriete']"));
        int priceValue = Integer.parseInt(hiddenPriceLocator.getAttribute("value"));
        if(priceValue==2000000){
            System.out.println("price value is 2000000");
        }

        String stylePercent = priceSlideLocator.getAttribute("style");
        if(stylePercent.contains("left: 100%")){
            System.out.println("slide is 100%");
        }

        priceSlideLocator = driver.findElement(By.xpath("//div[@class='slider-handle min-slider-handle custom']"));
        slideTrack = driver.findElement(By.xpath("//div[@class='slider-track-high']"));
        sliderSize = slideTrack.getSize();
        //sliderWidth = sliderSize.getWidth();
        xCoord = priceSlideLocator.getLocation().getX();
        System.out.println(xCoord);
        Thread.sleep(10);
        Actions builder2 = new Actions(driver);
        builder2.moveToElement(priceSlideLocator).click().dragAndDropBy(priceSlideLocator,-(xCoord+sliderWidth),0).build().perform();
        System.out.println("slide BACK%");

        hiddenPriceLocator = driver.findElement(By.xpath("//input[@id='sliderPrixPropriete']"));
        //priceValue = Integer.parseInt(hiddenPriceLocator.getAttribute("value"));
        WebElement plusButton = driver.findElement(By.id("PrixProprietePlus"));
        for(int i=0; i<2;i++){
            plusButton.click();
            priceValue = Integer.parseInt(hiddenPriceLocator.getAttribute("value"));
            if(priceValue==500000){
                System.out.println("purchase price is 500000");
            }

        }

        WebElement downPlusButton = driver.findElement(By.id("MiseDeFondPlus"));
        downPlusButton.click();
        WebElement downHiddenPrice = driver.findElement(By.id("sliderMiseDeFond"));
        String downPrice=downHiddenPrice.getAttribute("value");
        int downPricevalue = Integer.parseInt(downPrice);
        System.out.println("Down payment is " + downPricevalue);

 code to check the visibility   


    if (driver.findElement(By.xpath("//select[@id='Amortissement']")).isDisplayed()) {
            System.out.println("Element is Visible");
        } else {
            System.out.println("Element is InVisible");
        }

        //To check Element Present


if (driver.findElements(By.xpath("//select[@id='Amortissement']")).size() != 0) {
        System.out.println("Element is Present");
    } else {
        System.out.println("Element is Absent");
    }

    //To check Enable
    if (driver.findElement(By.xpath("//select[@id='Amortissement']")).isEnabled()) {
        System.out.println("Element is Enable");
    } else {
        System.out.println("Element is Disabled");
    }
    /*WebElement drpAmortization = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//select[@id='Amortissement']")));
    Select dropDownAmortization = new Select(drpAmortization);
    dropDownAmortization.selectByVisibleText("20 years");*/

    WebElement drpAmortization = driver.findElement(By.xpath("//select[@id='Amortissement']"));
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    //executor.executeScript("arguments[0].click();", drpAmortization);
    executor.executeScript("window.document.getElementById('Amortissement').click()");
    Select dropDownAmortization = new Select(drpAmortization);
    dropDownAmortization.selectByVisibleText("20 years");

    }


}

摊销下拉元素有问题

WebElement drpAmortization = driver.findElement(By.xpath("//select[@id='Amortissement']"));

【问题讨论】:

  • 你的代码有点大,你能不能去掉方法1和一些不需要的代码,只提供你遇到问题的代码...你也可以去掉你的断言条件等等。否则请给我下拉元素的网址。我会检查的。
  • 是的,您可以查看以下链接的摊销下拉列表ia.ca/mortgage-payment-calculator

标签: selenium webdriver


【解决方案1】:

我检查了页面的html代码,下拉不是常规的选择下拉。它只是一个按钮之类的东西。所以方法如下,

  1. 点击向下箭头按钮:

    driver.findElement(By.xpath("//*[@id='form_calculateur_versements']/div[4]//b")).click();
    

现在选项将可见。

  1. 从下拉列表中选择选项:

    driver.findElement(By.xpath("//*[@id='form_calculateur_versements']/div[4]//li[2]")).click();
    

我正在从上面代码的下拉菜单中选择第二个选项。

类似的方法适用于页面中的所有下拉菜单。

希望这对您有所帮助。谢谢。

【讨论】:

    【解决方案2】:

    摊销下拉不是标准的选择控件,因此您使用的 xpath 将不起作用。此外,标准 Webdriver API(例如 selectByVisibleText 等)不能用于从此类下拉列表中选择值。但是,您可以编写自己的自定义通用方法来从中选择值,如下所示:

    public static void selectText(String dropDownLabel, String value) {
      String showOptions = "//label[normalize-space(text())='" + dropDownLabel + "']/following::b[1]";
    
      driver.findElement(By.xpath(showOptions)).click();
      WebDriverWait wait = new WebDriverWait(driver, 10);
      String option = "//label[normalize-space(text())='" + dropDownLabel + "']/following::li[normalize-space(text())='"
              + value + "']";
      wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath(option))));
    
      driver.findElement(By.xpath(option)).click();
    }
    

    在上面的代码中,点击下拉菜单后,Webdriver 将等待下拉选项出现,然后点击所需的选项。如果您有其他疑问,请告诉我。

    【讨论】:

      【解决方案3】:

      这是您问题的答案:

      关于解决方案的几句话:

      1. 在没有ExpectedCondition 的情况下引入ExplicitWait 会破坏在wait=new WebDriverWait(driver, 50); 中成为Eplicit 的目的,您可以考虑将其删除。
      2. xpath //div[@class='slider-handle min-slider-handle custom'] 不是唯一的。您可以考虑构建一个唯一的 xpath。
      3. xpath //div[@class='slider-track-high'] 不是唯一的。您可以考虑构建一个唯一的 xpath。
      4. 您已经从java.awt.Toolkit; 导入了Dimension 类,而不是您可以考虑从org.openqa.selenium.Dimension; 导入Dimension
      5. 根据最佳编程实践,您可以考虑删除所有 Thread.sleep(); 并替换为 ExplicitWait
      6. AmortizationModal Dropdown,因此您可以考虑正确处理它。
      7. 您可以考虑从代码块中删除不必要的导入作为org.junit.Assert;,因为它从未实现过。
      8. 这是您自己的代码,稍作调整,在控制台上的程序末尾打印Value selected from Dropdown is : 20 years

        import java.util.List;
        
        import org.openqa.selenium.By;
        import org.openqa.selenium.Dimension;
        import org.openqa.selenium.JavascriptExecutor;
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.chrome.ChromeDriver;
        import org.openqa.selenium.chrome.ChromeOptions;
        import org.openqa.selenium.interactions.Actions;
        
        public class Q44226865_select_dropdown_list 
        {
        
            public static void main(String[] args) throws Exception 
            {
        
        
            WebDriver driver;
            String innerhtml = null;
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
        
            //approach 1 - to maximize screen in chrome
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--start-maximized");
            driver = new ChromeDriver(options);
            driver.get("http://ia.ca/");
            driver.findElement(By.xpath("//*[@id='nav-secondaire']//a[@data-utag-name='loans']")).click();
        
            driver.findElement(By.xpath("//a[contains(text(),'Mortgages')]")).click();
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("scroll(255, 644)");
            driver.findElement(By.xpath("//a[contains(.,'Calculate your payments')]")).click();
        
            WebElement priceSlideLocator = driver.findElement(By.xpath("//div[@class='slider-handle min-slider-handle custom']"));
            WebElement slideTrack = driver.findElement(By.xpath("//div[@class='slider-track-high']"));
            Dimension sliderSize = slideTrack.getSize();
            int sliderWidth = sliderSize.getWidth();
            int xCoord = priceSlideLocator.getLocation().getX();
            System.out.println(xCoord);
            System.out.println(sliderWidth);
            Thread.sleep(10);
        
            Actions builder = new Actions(driver);
            builder.moveToElement(priceSlideLocator)
            .click()
            .dragAndDropBy(priceSlideLocator, xCoord+sliderWidth,0)
            .build()
            .perform();
        
            WebElement hiddenPriceLocator = driver.findElement(By.xpath("//input[@id='sliderPrixPropriete']"));
            int priceValue = Integer.parseInt(hiddenPriceLocator.getAttribute("value"));
            if(priceValue==2000000){
                System.out.println("price value is 2000000");
            }
        
            String stylePercent = priceSlideLocator.getAttribute("style");
            if(stylePercent.contains("left: 100%")){
                System.out.println("slide is 100%");
            }
        
            priceSlideLocator = driver.findElement(By.xpath("//div[@class='slider-handle min-slider-handle custom']"));
            slideTrack = driver.findElement(By.xpath("//div[@class='slider-track-high']"));
            sliderSize = slideTrack.getSize();
            //sliderWidth = sliderSize.getWidth();
            xCoord = priceSlideLocator.getLocation().getX();
            System.out.println(xCoord);
            Thread.sleep(10);
            Actions builder2 = new Actions(driver);
            builder2.moveToElement(priceSlideLocator).click().dragAndDropBy(priceSlideLocator,-(xCoord+sliderWidth),0).build().perform();
            System.out.println("slide BACK%");
        
            hiddenPriceLocator = driver.findElement(By.xpath("//input[@id='sliderPrixPropriete']"));
            //priceValue = Integer.parseInt(hiddenPriceLocator.getAttribute("value"));
            WebElement plusButton = driver.findElement(By.id("PrixProprietePlus"));
            for(int i=0; i<2;i++){
                plusButton.click();
                priceValue = Integer.parseInt(hiddenPriceLocator.getAttribute("value"));
                if(priceValue==500000){
                    System.out.println("purchase price is 500000");
                }
        
            }
        
            WebElement downPlusButton = driver.findElement(By.id("MiseDeFondPlus"));
            downPlusButton.click();
            WebElement downHiddenPrice = driver.findElement(By.id("sliderMiseDeFond"));
            String downPrice=downHiddenPrice.getAttribute("value");
            int downPricevalue = Integer.parseInt(downPrice);
            System.out.println("Down payment is " + downPricevalue);
        
            if (driver.findElement(By.xpath("//select[@id='Amortissement']")).isDisplayed()) {
                System.out.println("Element is Visible");
            } else {
                System.out.println("Element is InVisible");
            }
        
            //To check Element Present
        
        
            if (driver.findElements(By.xpath("//select[@id='Amortissement']")).size() != 0) {
                System.out.println("Element is Present");
            } else {
            System.out.println("Element is Absent");
            }
        
            //To check Enable
            if (driver.findElement(By.xpath("//select[@id='Amortissement']")).isEnabled()) {
                System.out.println("Element is Enable");
            } else {
                System.out.println("Element is Disabled");
            }
        
            WebElement drpAmortization = driver.findElement(By.xpath("//form[@id='form_calculateur_versements']/div[4]/div/div/div[2]/b"));
            drpAmortization.click();
            List <WebElement> drpAmortization_list = driver.findElements(By.xpath("//form[@id='form_calculateur_versements']//div[@class='selectric-scroll']/ul/li"));
            System.out.println("Number of Elements : "+drpAmortization_list.size());
        
            for (int i=0; i<drpAmortization_list.size(); i++)
            {
                WebElement my_element = drpAmortization_list.get(i);
                innerhtml = my_element.getAttribute("innerHTML");
        
                if(innerhtml.contains("20 years"))
                {
                    Thread.sleep(3000);
                    my_element.click();
                    break;
                }
            }
            System.out.println("Value selected from Dropdown is : "+innerhtml);
          }
        
        }
        

      如果这能回答您的问题,请告诉我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-15
        • 2020-03-11
        • 2015-08-04
        相关资源
        最近更新 更多