自动提示文本的xpath自动travelocity.com失败



我一直在尝试多种方法来生成正确的xpath,以便在travelocity.com上单击第一个自动建议的文本。但是xpath无法定位元素。下面是我的代码。有人能帮我做正确的xpath吗。

package com.travel.city;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Booking {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "/Users/owner/desktop/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.travelocity.com");
driver.findElement(By.id("tab-flight-tab-hp")).click();
driver.findElement(By.id("flight-origin-hp-flight")).sendKeys("LAX");
driver.findElement(By.xpath("//div[@class='multiLineDisplay'] [contains(text(),'Los Angeles, CA, United States')]/parent::span[@class='text']")).click();
driver.findElement(By.id("flight-destination-hp-flight")).sendKeys("DEN");
driver.findElement(By.xpath("//div[@class='multiLineDisplay']/[contains(text(),'Denver, United States of America')]/parent::span[@class='text']")).click();
}
}

好吧,有两件事。首先,通过使用WebDriverWait对象等待建议来改进您的测试组织,其次,在编写代码之前,在chrome控制台中调试您的xpath定位器。在代码片段中,两个定位器都不正确。这应该做得更好:

WebDriverWait wait = new WebDriverWait(driver, 5);
driver.get("http://www.travelocity.com");
driver.findElement(By.id("tab-flight-tab-hp")).click();
driver.findElement(By.id("flight-origin-hp-flight")).sendKeys("LAX");
wait.until(
ExpectedConditions.presenceOfElementLocated(
By.xpath("//div[contains(text(), 'Los Angeles, CA, United States')]")));
driver.findElement(By.xpath(
"//div[contains(text(), 'Los Angeles, CA, United States')]")).click();
driver.findElement(By.id("flight-destination-hp-flight")).sendKeys("DEN");
wait.until(
ExpectedConditions.presenceOfElementLocated(By.xpath(
"//a[@data-value = 'Denver (DEN-All Airports)']")));
driver.findElement(By.xpath(
"//a[@data-value = 'Denver (DEN-All Airports)']")).click();

您需要更改您的xpath,如下所示。

工作代码:

public static void main(String args[]){
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.travelocity.com");
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Wander"));

driver.findElement(By.id("tab-flight-tab-hp")).click();
driver.findElement(By.id("flight-origin-hp-flight")).sendKeys("LAX");
driver.findElement(By.xpath("//ul[@class='results']//div[@class='multiLineDisplay' and contains(text(),'Los Angeles, CA, United States')]")).click();
driver.findElement(By.id("flight-destination-hp-flight")).sendKeys("DEN");
driver.findElement(By.xpath("//ul[@class='results']//div[@class='multiLineDisplay' and contains(text(),'United States of America')]")).click();
}

最新更新