Java 如何选择下拉选项

Java 如何选择下拉选项,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我想使用Selenium查找以下下拉选项,但我无法这样做 Arial 信使 日内瓦 赫尔维蒂卡 机器人 无衬线 SourceSansPro 新罗马时代 威尔达纳 信使 如何选择以下下拉选项。我一直无法找到元素。请建议 我尝试了以下两种变体: List<WebElement> b = driver.findElements( By.xpath("//div[@class='fontDropDown']")); new Select(b.get(1).findElement(

我想使用Selenium查找以下下拉选项,但我无法这样做


Arial
信使
日内瓦
赫尔维蒂卡
机器人
无衬线
SourceSansPro
新罗马时代
威尔达纳
信使
如何选择以下下拉选项。我一直无法找到元素。请建议

我尝试了以下两种变体:

List<WebElement> b = driver.findElements(
    By.xpath("//div[@class='fontDropDown']"));
new Select(b.get(1).findElement(
    By.xpath("//select[text()='Helvetica']")));
Select select = new Select(b.get(1).findElement(By.tagName("select")));

// Select by value (the attribute)
select.selectByValue("Helvetica");

// Select by visible text (the text inside the tag)
select.selectByVisibleText("Helvetica");
List b=driver.findElements(
xpath(“//div[@class='fontDropDown']”);
新选择(b.get(1).findElement(
xpath(//选择[text()='Helvetica']);
无法定位哪个元素抛出。及

List<WebElement> b = driver.findElements(
    By.xpath("//div[@class='fontDropDown']"));
new Select(b.get(1).findElement(
    By.xpath("//select/option[text()='Helvetica']")))
List b=driver.findElements(
xpath(“//div[@class='fontDropDown']”);
新选择(b.get(1).findElement(
xpath(“//选择/选项[text()='Helvetica']”)

产生元素的方法应该是
select
,而不是
option

您的第一种方法没有找到元素,因为该值在选项中,而不是在select元素中

第二种方法更好,但您尝试将结果包装在
Select
中。这不起作用,因为该方法返回选项字段的句柄。因此,不要将
Select
包装在以下内容周围,将其转换为
WebElement

WebElement option = b.get(1).findElement(
    By.xpath("//select/option[text()='Helvetica']"));

由于您希望选择此选项,因此您实际上应该关注访问
选择
元素,然后使用其方法选择其中一个选项。因此,请查看
选择的功能

以下是两种变体:

List<WebElement> b = driver.findElements(
    By.xpath("//div[@class='fontDropDown']"));
new Select(b.get(1).findElement(
    By.xpath("//select[text()='Helvetica']")));
Select select = new Select(b.get(1).findElement(By.tagName("select")));

// Select by value (the attribute)
select.selectByValue("Helvetica");

// Select by visible text (the text inside the tag)
select.selectByVisibleText("Helvetica");

请包括代码和HTML作为文本,而不是图像,非常感谢。因此,请编辑您的问题。请注意,
get(1)
访问第二个匹配元素,而不是第一个(索引从
0
开始)。我不确定你是否想要(看不到整个HTML)。另外,请确保您要查找的是
选择
字段,而不是
选项
字段?@Zabuza,谢谢您的反馈。是的,我想要第二个匹配的元素。我已经将它更新为选择字段,它仍然抛出相同的错误“元素无法定位”好的。但请相应地编辑您的问题(包括HTML代码)。另外,请使用编辑器的格式选项,尤其是代码。然后你会得到我的支持,可能会从其他人那里得到更多的帮助。非常感谢。我会尽力让你知道的。