首页 > 解决方案 > expedia“从”机场列表中的自动下拉列表

问题描述

我需要您的帮助,我正在尝试在 www.Expedia.com 的“从”下选择机场名称的自动下拉列表。我的代码成功运行但没有生成所需的输出。

使用这行代码,我将密钥发送到“flying from”

driver.findElement(By.xpath("//input[@placeholder='City or airport']")).sendKeys("London");

然后使用此代码,我试图从自动下拉列表中捕获希思罗机场,但我的代码不是英国伦敦(LHR-希思罗机场),而是选择英国伦敦(STN-斯坦斯特德)。

        List<WebElement> list = driver.findElements((By.xpath("//div[@class='autocomplete-dropdown']")));
    for (int i=0;i<list.size();i++){
        System.out.println(list.get(i).getText());
        if(list.get(i).getText().contains("Heathrow")){
            list.get(i).click();
            break;
        }
    }

当前产出:英国伦敦(SEN-绍森德) 预期产出:英国伦敦(LHR-希思罗)

下面是我试图点击自动建议的代码

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;

public class expedia_search {
public static void main (String args[]) {
    // Set the property for webdriver.chrome.driver to be the location to your local download.
    System.setProperty("webdriver.chrome.driver", "/Users/vc/IdeaProjects/expedia_search/src/chromedriver");

    // Create new instance of ChromeDriver
    WebDriver driver = new ChromeDriver();

    // And now use this to visit expedia.com
    driver.get("http://www.expedia.com");

    // Find the text input element by its absolute path(xpath)
    WebElement element = driver.findElement(By.xpath("//*[@id=\"tab-flight-tab-hp\"]"));

    // Once flight tab selected click on it
    element.click();

    //type london on Expedia from tab
    driver.findElement(By.xpath("//input[@placeholder='City or airport']")).sendKeys("London");

    //capture auto suggestions from expedia from
    List<WebElement> list = driver.findElements((By.xpath("//div[@class='autocomplete-dropdown']")));
    for (int i=0;i<list.size();i++){
        System.out.println(list.get(i).getText());
        if(list.get(i).getText().contains("Heathrow")){
            list.get(i).click();
            break;
        }
      }

    }
 }

标签: javaseleniumselenium-webdriver

解决方案


欢迎来到 SO。这是可用于直接选择机场而不使用循环的 xpath 和 css。

CSS:

.autocomplete-dropdown a[data-value*='LTN']

xpath: //div[@class='autocomplete-dropdown']//a[contains(@data-value,'Luton')]

硒实现:

driver.findElement(By.xpath("//div[@class='autocomplete-dropdown']//a[contains(@data-value,'Luton')]")).click();

或者

driver.findElement(By.cssSelector(".autocomplete-dropdown a[data-value*='Luton']")).click();

推荐阅读