如何使用 Selenium 和 Java 从下拉框中获取可用选项?

How do I use Selenium and Java to get the options available from a drop down box?

我正在尝试使用 Selenium 从 Autotrader 网站检索所有汽车制造商。有一个下拉框会根据给定时间可供出售的汽车而变化。

我已经尝试了 Whosebug 上列出的许多解决方案,但我的代码没有 return 任何东西。

如有任何帮助,我们将不胜感激!

这是我的代码...

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.Select;


public class AutotraderScraper {

    public static void main(String[] args) throws InterruptedException
    {

        WebDriver driver = new HtmlUnitDriver();

        // Visit autotrader website
        driver.get("http://www.autotrader.co.uk/");

        // Look for car make box
        Select select = new Select(driver.findElement(By.id("searchVehiclesMake")));

        // Get all options
        List<WebElement> allOptions = select.getOptions();

        // Iterate through available options
        java.util.Iterator<WebElement> i = allOptions.iterator();

        // Print options
        while(i.hasNext()) {
            WebElement row = i.next();
            System.out.println("Found an option!");
            System.out.println(row.getText());
        }
    }
}

这是一个重复的 ID,正在该页面的两个不同位置使用。

建议你用xpathselect element下面的xpath可以用

//h1[.='Find new & used cars']/..//*[@id='searchVehiclesMake']

查找新车和二手车部分中的目标元素