我需要在自动填充文本框中输入一些文字。 然后我将从该自动填充选项中选择一个选项,并需要单击它。
我尝试过使用以下代码:
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String textToSelect = "headlines today";
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
Thread.sleep(2000);
WebElement autoOptions= driver.findElement(By.id("lst-ib"));
autoOptions.sendKeys("he");
List<WebElement> optionsToSelect = driver.findElements(By.tagName("li"));
for(WebElement option : optionsToSelect){
System.out.println(option);
if(option.getText().equals(textToSelect)) {
System.out.println("Trying to select: "+textToSelect);
option.click();
break;
}
}
答案 0 :(得分:1)
你可以这样做我用google主页自动建议作为例子
public class AutoSelection {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("mahatama gandhi");
List<WebElement> autoSuggest = driver.findElements(By
.xpath("//div[@class='sbqs_c']"));
// verify the size of the list
System.out
.println("Size of the AutoSuggets is = " + autoSuggest.size());
// print the auto suggest
for (WebElement a : autoSuggest)
System.out.println("Values are = " + a.getText());
// suppose now you want to click on 3rd auto suggest then simply do like
// this
autoSuggest.get(2).click();
}
}
答案 1 :(得分:0)
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String textToSelect = "headlines today";
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
Thread.sleep(2000);
WebElement autoOptions= driver.findElement(By.id("lst-ib"));
autoOptions.sendKeys("he");
List<WebElement> optionsToSelect = driver.findElements(By.xpath("//div[@class='sbqs_c']"));
for(WebElement option : optionsToSelect){
System.out.println(option);
if(option.getText().equals(textToSelect)) {
System.out.println("Trying to select: "+textToSelect);
option.click();
break;
}
}
答案 2 :(得分:0)
driverName.findElement(By.xpath("XPATH Location")).sendKeys("KeyNameYouWantToSearch" , Keys.TAB);
答案 3 :(得分:0)
我们可以使用Java 8流API来过滤和收集数组中的Web元素。使用索引会更容易点击。
//收集5个自动完成条目列表
List<WebElement> list = driver.findElements(By.cssSelector("#ui-id-1
li:nth-child(n)")).stream()
.limit(5)
.collect(Collectors.toList());
//这将单击自动完成列表中的第一个元素
list.get(0).click();