Selenium WebDriver Java:WebElement列表大小显示0的问题排查
解决Expedia出发地自动建议列表获取失败问题
问题根源分析
- 无显式等待,元素未完成加载
硬编码的Thread.sleep(2000)无法保证自动建议列表在获取元素前完成渲染,导致获取到空集合。 - 定位器依赖动态属性
原代码使用的id='origin_select-menu'属于动态生成属性,页面更新后可能失效,无法定位到目标元素。 - 输入操作对象错误
直接向触发按钮Leaving from执行sendKeys,未激活内部的实际输入框,导致自动建议未被触发。
修复后的代码示例
package pkg; import java.util.List; import java.time.Duration; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; public class Booking { ChromeDriver driver; String baseurl="https://www.expedia.co.in/Flights"; @Before public void setup() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); } @Test public void functions() throws InterruptedException { driver.get(baseurl); driver.manage().window().maximize(); // 选择舱位部分保留原逻辑(若正常工作) WebElement dropdown= driver.findElement(By.xpath("//span[text()='Economy']")); dropdown.click(); List <WebElement> drop=driver.findElements(By.xpath("//div[@class='uitk-list uitk-type-400']//span")); for(int i=0;i<drop.size();i++) { System.out.println(drop.get(i).getText()); if(drop.get(i).getText().contains("First class")) { drop.get(i).click(); break; } } // 修复后的出发地选择逻辑 // 1. 点击出发地按钮激活输入框 WebElement fromButton = driver.findElement(By.xpath("//button[@aria-label='Leaving from']")); fromButton.click(); // 2. 等待输入框可见并输入文本 WebElement fromInput = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@aria-label='Leaving from']"))); fromInput.sendKeys("Brussels (BRU - All Airports) Belgium"); // 3. 等待自动建议列表加载完成 List<WebElement> suggestions = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfAllElementsLocatedBy( By.xpath("//li[contains(@data-stid, 'origin_select-result-item')]"))); System.out.println("Size:" + suggestions.size()); // 4. 遍历选择目标选项 for (WebElement suggestion : suggestions) { if (suggestion.getText().contains("Brussels (BRU - All Airports) Belgium")) { suggestion.click(); break; } } Thread.sleep(2000); // driver.quit(); } }
关键优化点
- 显式等待替代硬休眠:使用
WebDriverWait结合ExpectedConditions,确保元素在可交互状态下再执行操作,提升稳定性。 - 稳定定位器:用
contains(@data-stid, 'origin_select-result-item')替代精确ID,避免动态属性变化导致定位失效。 - 正确操作输入框:先点击触发按钮激活输入框,再向实际输入框输入文本,确保自动建议被正常触发。
内容的提问来源于stack exchange,提问作者Coder
相关产品推荐
相关产品推荐

