如何将文本发送到在 selenium webdriver 中使用自动完成的搜索框

How to send text to the search box which uses autocomplete in selenium webdriver

我正在尝试使用此网站预订航班 https://www.phptravels.net/

有一个文本框,您可以在其中开始输入您的航班始发机场,它会为您提供自动完成建议,即使我在文本框上使用 'inspect element' 也找不到,这是我找到的 xpath:

driver.findElement(By.xpath("//*[@id=\"select2-drop\"]/div/input")).click();

我收到以下错误:

Unable to locate element: {"method":"xpath","selector":"//*[@id="select2-drop"]/div/input"}

知道如何定位文本框元素吗?

网站的HTML有点棘手。 您的输入 //*[@id='select2-drop']/div/input 是 "hidden"(html 和 selenium 的观点)。

您需要单击特定元素://*[@id='flights']/form/div[1] 使其成为 "visible"。

所以你的代码需要像这样:

//After click on FLIGHTS...

driver.findElement(By.xpath("//*[@id='flights']/form/div[1]")).click();
Thread.sleep(2*1000);

driver.findElement(By.xpath("//*[@id='select2-drop']/div/input")).sendKeys("Moon");
Thread.sleep(2*1000);

如果你想编写更好的 Selenium 代码,我建议你阅读 explicit wait

使用显式等待,您的代码将如下所示:

(new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='flights']/form/div[1]"))).click();

(new WebDriverWait(driver, 10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='select2-drop']/div/input")).sendKeys("Moon");

看起来更糟,但更好。

编辑 1

获取建议列表:

//after type in input, put a wait to be sure the suggestion list is loaded.

List<WebElement> list = driver.findElements(By.xpath("//*[@id='select2-drop']/ul/li/div"));

for(WebElement aux : list) {

    System.out.println(aux.getText());

}

在网页 https://www.phptravels.net/ 上单击 FLIGHTS 选项卡并将字符序列发送到搜索框示例 Pune您可以使用以下解决方案:

driver.get("https://www.phptravels.net/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(.,'Flights')]"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[@class='select2-chosen' and contains(.,'Enter City Or Airport')]")))click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='select2-search']/input[@class='select2-input select2-focused']"))).sendKeys("Pune");

以下代码可用于 select 自动完成搜索框中的第一个建议值。

new WebDriverWait(driver, 
20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='select2- 
search']/input[@class='select2-input select2-focused']"))).sendKeys(Keys.ArrowDown);

new WebDriverWait(driver, 
20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='select2- 
search']/input[@class='select2-input select2-focused']"))).sendKeys(Keys.Enter);