[英]How do I use Selenium and Java to get the options available from a drop down box?
I'm trying to use Selenium to retrieve all the car makes from the Autotrader website. 我正在尝试使用Selenium从Autotrader网站检索所有汽车制造商。 There is a drop-down box that changes depending on which cars are available for sale at a given time.
有一个下拉框根据在给定时间可出售的汽车而变化。
I have tried many of the solutions listed on stackoverflow, but my code doesn't return anything. 我已经尝试了stackoverflow上列出的许多解决方案,但是我的代码未返回任何内容。
Any help would be greatly appreciated! 任何帮助将不胜感激!
Here is my code... 这是我的代码...
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());
}
}
}
This is a duplicate id and is being used in two different places of this page. 这是重复的ID,并在此页面的两个不同位置使用。
I suggest you use xpath
to find the select element
The following xpath
can be used 我建议您使用
xpath
查找select element
可以使用以下xpath
//h1[.='Find new & used cars']/..//*[@id='searchVehiclesMake']
Target element in Find new & used cars section 查找新车和二手车部分中的目标元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.