无法获取下拉菜单中所有选项的文本

问题描述

我正在尝试获取选择语言下拉列表中所有选项的文本。

但是我无法得到它们。

仅打印下拉菜单中所有选项中的“英语(英国)”。其余所有语言均显示为空白。

下面是我的代码

System.setProperty(“ webdriver.chrome.driver”,“ D:\ 1 \ chromedriver.exe”);

    // Start browser
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
    driver.manage().timeouts().implicitlyWait(15,TimeUnit.SECONDS);

    driver.get("https://accounts.google.com/ServiceLogin/identifier?elo=1&flowName=GlifWebSignIn&flowEntry=AddSession");

    driver.findElement(By.xpath("//div[@class = 'TquXA']")).click();

    List<WebElement> listofLanguages = driver.findElements(By.xpath("//span[@class = 'vRMGwf oJeWuf']"));
    
    int size = listofLanguages.size();
    
    for(int i = 0; i<size; i++) {
        
        WebElement ele = listofLanguages.get(i);
        String value = ele.getText();
        System.out.println("languages are : "+value);
    }
    

    driver.quit();

解决方法

在您检索文本时,可能不会立即加载语言下拉列表。尝试使用explicitwait条件,以确保所有下拉列表元素在DOM中都是可见的。

    WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfAllElementsLocated(By.xpath("//span[@class = 'vRMGwf oJeWuf']")));

如果在20秒内不可见,则上面的代码将引发TimeOutException。

此外,每当打印文本时,最好使用foreach循环来获取动态的元素数量。

另一种选择是使用睡眠,单击后睡眠3秒钟。 (虽然它对您有用,但这不是最佳方法) 例如:Thread.sleep(3000);