2017-02-17 41 views
1

爲什麼我的代碼不能可靠地點擊下拉菜單項?爲什麼我的代碼不能可靠地點擊下拉菜單項?

  1. 我的代碼dosnt可靠地點擊預期的下拉菜單項。
  2. 例如,如果我執行相同的測試100次,12個測試將失敗,因爲該方法不會選擇想要的菜單項可以說(Mr),即使使用發送鍵也會出現相同的問題。
  3. 我已經設置了等待時間x30秒等待元素可見,甚至等待元素可點擊發生同樣的問題。
  4. 例如請參閱下面的dropwdown項目:

    <select id="titlefield" class="form-control ng-pristine ng-untouched ng-invalid ng-invalid-required" name="Salutation" ng-model="PersonalDetails.Salutation" ng-options="salut.id as salut.id for salut in Salutations" ng-required="FlowData.IsGuest" required="required"> 
    <option class="ng-binding" value="">Please select</option> 
    <option value="0" label="Mr.">Mr.</option> 
    <option value="1" label="Miss">Miss</option> 
    <option value="2" label="Mrs.">Mrs.</option> 
    <option value="3" label="Ms.">Ms.</option> 
    <option value="4" label="Dr.">Dr.</option> 
    

  5. 我的代碼構造如下:

    public void selectTitleFromDropdownMenu(WebElement dropdown, String textToSearchFor) { 
    Wait<WebDriver> tempWait = new WebDriverWait(this.driver, 30); 
    try { 
        tempWait.until(ExpectedConditions.visibilityOf(dropdown)); 
        List<WebElement> options = dropdown.findElements(By.tagName("option")); 
        Select selectDropdown = new Select(dropdown); 
        for (int i = 0; i < options.size(); i++) { 
         if (options.get(i).getText().equals(textToSearchFor)) { 
          selectDropdown.selectByVisibleText(textToSearchFor); 
          System.out.println("Successfully selected the following text: " + textToSearchFor + ", using the following webelement: " + "<" + dropdown.toString() + ">"); 
         } 
        } 
    
    }catch(Exception e) { 
        System.out.println("Unable to select the following text: " + textToSearchFor + ", using the following WebElement: " + "<" + dropdown.toString() + ">"); 
        Assert.assertFalse(true, "Unable to select the required text from the dropdown menu, Exception: " + e.getMessage()); 
    } 
    

    }

enter image description here

+0

參考提供過來的解決方案。它會幫助你。 http://stackoverflow.com/questions/30184055/selenium-select-value-from-a-drop-down-which-is-dependent-on-value-selected-in – Abhinav

回答

0

您需要在下拉菜單上而不是在選項上創建選擇對象。另外,你不需要任何for循環。

List<WebElement> options = dropdown.findElements(By.Id("titlefield")); 
Select selectDropdown = new Select(dropdown); 
selectDropdown.selectByVisibleText(textToSearchFor); 
+0

感謝您的評論,列表將如何項目存儲列表的值,如果它只涉及選擇的項目? – Gbru

+0

@ Phil_P85我不是webdriver API的內部,但它就是這樣工作的。 –

+0

ok @Gaurang Shah再次感謝我會試一試 – Gbru

0

你可以用這個也嘗試:
Select selectDropdown = new Select(driver.findElement(By.id("titlefield"))); selectDropdown.selectByVisibleText(textToSearchFor);

+1

selectDropdown.selectByVisibleText(「textToSearchFor」); - textToSearchFor不應該在雙引號中...否則硒將搜索此字符串而不是變量textToSearchFor的內容。 – Grasshopper

相關問題