我在Keys类中使用cssselector。但是没有选择值
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes", Keys.DOWN, Keys.ENTER);
我要从下拉列表中选择值敖德萨:
答案 0 :(得分:0)
有多种处理下拉值的方法
- dropdown.selectByVisibleText("Text");
- dropdown.selectByIndex(2); (Index starts with zero always in list)
- dropdown.selectByValue(“Text”)
示例代码:
Select oSelect = new Select(driver.findElement(By.cssSelector("input[id='loadingPort']")));
// Select option (Odessa(UKR))
oSelect.selectByVisibleText("Odessa(UKR)"); // Using sleep command so that changes can be noticed
Thread.sleep(2000);
// : Select option 'using Index
oSelect.selectByIndex(1);
Thread.sleep(2000);
// Print all the options for the selected drop down and select one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();
// Setting up the loop to print all the options
for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
// Putting a check on each option that if any of the option is equal to 'Africa" then select it
if(sValue.equals("Odessa(UKR)")){
oSelect.selectByIndex(i);
break;
}
}
答案 1 :(得分:0)
我不确定网站是如何填充该下拉菜单的,但是也许您可以输入文本,然后选择第一个选项,如下所示:
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes");
browser.findElement(By.cssSelector("input[id='loadingPort']")).findElements(By.tagName("option")).get(0).click()
/** OR */
browser.findElement(By.cssSelector("input[id='loadingPort']:first-child")).click()
对不起,我不熟悉java或cssSelectors ...只是Selenium。如果您可以清理该代码,则在网站向dom动态添加选项的情况下应该可以使用。
再使用xpath:
browser.findElement(By.xpath("input[@id='loadingPort']/option[1]")).click()