我想选择自动完成文本框中显示的第一个选项。下面是我尝试但未获得所需输出的代码。
public void clickSublink() throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
WebDriver dr=new ChromeDriver();
dr.get("http://demoqa.com/autocomplete/");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
dr.findElement(By.xpath("//ul[@id='ui-id-1']//child::li")).click();
}
要从autocomplete文本框中选择第一个选项,您需要使用elementToBeClickable()
,并且可以使用以下任何一个Locator Strategies:
cssSelector
:
driver.get("http://demoqa.com/autocomplete/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.ui-autocomplete-input#tags"))).sendKeys("b");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ul.ui-autocomplete>li>div"))).click();
xpath
:
driver.get("http://demoqa.com/autocomplete/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='ui-autocomplete-input' and @id='tags']"))).sendKeys("b");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='ui-menu ui-widget ui-widget-content ui-autocomplete ui-front']/li/div"))).click();
如果只选择第一个选项,则可以使用硒中的键类。请在下面的代码中找到相同的键。
public void clickSublink() throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
WebDriver dr=new ChromeDriver();
dr.get("http://demoqa.com/autocomplete/");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys(Keys.DOWN, Keys.ENTER);}