无法选择下拉列表,显示不可见

时间:2017-05-28 11:36:01

标签: selenium webdriver

以下代码无法选择“分期付款”下拉列表

   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']”));

3 个答案:

答案 0 :(得分:0)

我已经检查了页面的html代码,而下拉列表不是传统的选择下拉列表。它只是一个像按钮一样的按钮。所以方法如下,

  1. 单击向下箭头按钮:

    driver.findElement(By.xpath("//*[@id='form_calculateur_versements']/div[4]//b")).click();
    
  2. 现在可以看到选项。

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

      driver.findElement(By.xpath("//*[@id='form_calculateur_versements']/div[4]//li[2]")).click();
      
    2. 我从上面代码的下拉列表中选择了第二个选项。

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

      希望这会对你有所帮助。感谢。

答案 1 :(得分:0)

Amortization下拉列表不是标准的选择控件,因此您使用的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将等待下拉选项出现,然后单击所需的选项。如果您有进一步的疑问,请与我们联系。

答案 2 :(得分:0)

以下是您的问题的答案:

关于解决方案的几句话:

  1. 诱导ExplicitWait没有ExpectedCondition会违反wait=new WebDriverWait(driver, 50);中出现的隐含目的,您可以考虑将其删除。
  2. xpath //div[@class='slider-handle min-slider-handle custom']不是唯一的。您可以考虑构建一个唯一的xpath。
  3. xpath //div[@class='slider-track-high']不是唯一的。您可以考虑构建一个唯一的xpath。
  4. 您已从Dimension导入了java.awt.Toolkit;班级,而您可能会考虑从Dimension
  5. 导入org.openqa.selenium.Dimension;班级
  6. 根据最佳编程惯例,您可以考虑腾出所有Thread.sleep();并通过ExplicitWait替换
  7. AmortizationModal Dropdown,因此您可以考虑正确处理它。
  8. 您可以考虑将代码块中不必要的导入从org.junit.Assert;删除,因为它从未实现过。
  9. 以下是您自己的代码,其中包含一些最小的调整,在控制台的程序末尾打印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);
      }
    
    }
    
  10. 如果这回答你的问题,请告诉我。