Selenium技术问题:如何定位Spicejet网站的To输入字段?
Hey there! I’ve run into similar quirks with SpiceJet’s dynamic flight booking form before—let’s get that "TO" field working smoothly for you.
The Core Problem
When you click the "FROM" field, the page renders two sets of city options: one tied to the origin, another for the destination. Your original selector //a[@value='IXG'] targets the first matching element (which belongs to the "FROM" dropdown), not the one we need for "TO". Plus, the destination dropdown might not be fully active unless you first click its input box.
Reliable Solutions to Try
1. Activate the "TO" Field First, Then Select the City
This is the most robust approach, as it ensures you’re interacting with the correct dropdown context:
driver.get("http://www.spicejet.com/"); // Handle the FROM field driver.findElement(By.xpath("//*[@id='ctl00_mainContent_ddl_originStation1_CTXT']")).click(); driver.findElement(By.cssSelector("a[value='HYD']")).click(); // Activate the TO field, then pick your destination city driver.findElement(By.xpath("//*[@id='ctl00_mainContent_ddl_destinationStation1_CTXT']")).click(); driver.findElement(By.cssSelector("a[value='IXG']")).click();
2. Target the Second Matching Element Directly
If you want to skip clicking the TO input box, use an indexed XPath to select the second instance of the city element:
// After selecting the FROM city driver.findElement(By.xpath("(//a[@value='IXG'])[2]")).click();
Note: Only use this if you’re certain the second element will always be the destination option—dynamic pages can sometimes reorder elements, so the first method is safer long-term.
3. Add Explicit Waits (Critical for Dynamic Pages)
SpiceJet’s page loads content dynamically, so adding waits prevents "element not found" errors from slow loading:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; // ... driver.get("http://www.spicejet.com/"); WebDriverWait wait = new WebDriverWait(driver, 10); // Wait for FROM field to be clickable, then interact wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='ctl00_mainContent_ddl_originStation1_CTXT']"))).click(); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[value='HYD']"))).click(); // Wait for TO field, activate it, then select the destination wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='ctl00_mainContent_ddl_destinationStation1_CTXT']"))).click(); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[value='IXG']"))).click();
Why These Work
- Activating the TO field first switches the page’s focus to the destination dropdown, guaranteeing your selector targets the right element.
- Indexed XPaths bypass context switching but are less reliable if the page structure changes.
- Explicit waits handle dynamic content loading, which is super common on travel booking sites like SpiceJet.
内容的提问来源于stack exchange,提问作者Vignesh Vicky

