如何从下拉菜单中选择值

时间:2019-10-23 17:11:42

标签: selenium-webdriver

我正在尝试使表单自动化,并且下拉列表中没有单击

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

Screenshot的代码

我在索引中使用了选择方法,但没有用。 然后将Click与xpath一起使用,就可以了,但没有选择该值

代码-

                                选择一个行业                             

        农业       

获取“元素不可交互”

1 个答案:

答案 0 :(得分:0)

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);
 }