首页 > 解决方案 > 如何从下拉列表中选择值

问题描述

我正在尝试使表单自动化并且下拉菜单不要单击

driver.findElement(By.xpath("//select[@name='Lead.Step2.Industry']")).sendKeys("Agriculture");

代码截图

我使用带有索引的 select 方法,它不起作用。然后将 Click 与 xpath 一起使用,它可以工作,但未选择该值

编码 -

选择行业

农业

获取“元素不可交互”

标签: selenium-webdriver

解决方案


sendKeys 用于文本框中的类型值。如果是下拉输入,则需要使用 selectByVisibleText 或 selectByIndex。我希望它对你有帮助。

 WebElement mySelect = driver.findElement(By.xpath("//select[@name='Lead.Step2.Industry']"));
 Select mySelectd= new Select(mySelect);         
 mySelectd .selectByVisibleText("Agriculture");

它将在您的下拉菜单中选择“农业”选项。

如果您需要通过可见文本选择下拉菜单,您可以使用以下方法:

 public static void selectByVisible(WebElement lelement,String selectValue) {
    WebElement mySelect =lelement;                  
    Select mySelectd= new Select(mySelect);         
    mySelectd .selectByVisibleText(selectValue);
 }

如果您需要按索引选择下拉菜单,

public static void selectByIndex (WebElement lelement,int selectValue) {
    WebElement mySelect =lelement;                  
    Select mySelectd= new Select(mySelect);         
    mySelectd .selectByIndex(selectValue);
 }

推荐阅读