如何使用Selenium和Java从下拉框中获取可用选项?
我正在尝试使用Selenium从Autotrader网站检索所有汽车品牌。有一个下拉框,根据给定时间可供出售的汽车而变化 我已经尝试了stackoverflow上列出的许多解决方案,但我的代码没有返回任何结果 任何帮助都将不胜感激 这是我的密码如何使用Selenium和Java从下拉框中获取可用选项?,java,selenium,Java,Selenium,我正在尝试使用Selenium从Autotrader网站检索所有汽车品牌。有一个下拉框,根据给定时间可供出售的汽车而变化 我已经尝试了stackoverflow上列出的许多解决方案,但我的代码没有返回任何结果 任何帮助都将不胜感激 这是我的密码 import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebEleme
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());
}
}
}
import java.util.List;
导入org.openqa.selenium.By;
导入org.openqa.selenium.WebDriver;
导入org.openqa.selenium.WebElement;
导入org.openqa.selenium.htmlunit.HtmlUnitDriver;
导入org.openqa.selenium.support.ui.Select;
公共级自动雷达扫描器{
公共静态void main(字符串[]args)引发InterruptedException
{
WebDriver driver=新的HtmlUnitDriver();
//访问autotrader网站
驱动程序。获取(“http://www.autotrader.co.uk/");
//寻找汽车制造箱
选择=新选择(driver.findElement(By.id(“searchVehiclesMake”));
//获取所有选项
List allOptions=select.getOptions();
//遍历可用的选项
java.util.Iterator i=allOptions.Iterator();
//打印选项
while(i.hasNext()){
WebElement行=i.next();
System.out.println(“找到了一个选项!”);
System.out.println(row.getText());
}
}
}
这是一个重复的id,在本页的两个不同位置使用。
我建议您使用xpath
查找select元素
,可以使用以下xpath
//h1[.='Find new & used cars']/..//*[@id='searchVehiclesMake']
查找新车和二手车部分的目标元素
您是否尝试过使用Firefox或Chrome网络驱动程序?没有,您会推荐吗?它可以帮助识别罪犯,请尝试。我一定会尝试一下,并让您知道。我仍然很想知道是否有人也能帮助解决硒的问题。不,我的意思是,这仍然是一种硒特定的解决方案。我只是建议试试其他的驱动程序而不是HTMLUnit。谢谢你们的评论。我是网络应用程序新手,恐怕我不完全理解你的评论。请您解释一下,或者给我看一些示例代码好吗?不客气!请替换
Select=new Select(driver.findElement(By.id)(“searchVehiclesMake”)代码>使用Select=new-Select(driver.findelelement(By.xpath(“//h1[.='Find new&used cars']/../*[@id='searchVehiclesMake']));这将只返回您可能需要的元素
。看到我的第二个附件了吗?第二个屏幕截图上你想要的元素是什么?谢谢,它的构建和运行都很好,但是它仍然没有返回任何值。有什么想法吗?有什么例外吗?