java Selenium 发送键(文本),从下拉列表中选择并按 Enter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42870881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:55:46  来源:igfitidea点击:

Selenium send keys (text), selecting from dropdown and hit enter

javaseleniumdrop-down-menusendkeys

提问by Kevster

I'm trying to trawl this website: http://www.Hymanson-stops.co.uk/

我正在尝试浏览这个网站:http: //www.Hymanson-stops.co.uk/

The data is not showing in the URL so I'm using a chromedriver.

数据未显示在 URL 中,因此我使用的是 chromedriver。

My code is:

我的代码是:

   public static void main(String[] args) {
    //setup chromedriver
    File file = new File("C:\Users\USER\Desktop\chromedriver.exe");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver();
    try {
        driver.get("http://www.Hymanson-stops.co.uk/");
        //begin the simulation
        WebElement menu = driver.findElement(By.xpath("//*[@id=\"sliderLocation\"]"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
        menu.sendKeys("Knightsbridge");
        Thread.sleep(4000);
        Select menu2 = new Select(menu);
        menu2.selectByVisibleText("Knightsbridge");
        Thread.sleep(4000);
    } catch (Exception exp) {
        System.out.println("exception:" + exp);
        //close and quit windows
        driver.close();
        driver.quit();
    }
    //close and quit windows
    driver.close();
    driver.quit();
}

The error that I get is:

我得到的错误是:

   exception:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"

How would I be able to select a location and hit enter because I tried inspecting the HTML and the options are dynamically loaded so not visible!

我如何能够选择一个位置并按 Enter 键,因为我尝试检查 HTML 并且选项是动态加载的,因此不可见!

回答by RAJ

You are trying to select an element but it's not select list, it's a link, So all you have to do is to click that element, that's all

您正在尝试选择一个元素,但它不是选择列表,而是一个链接,所以您所要做的就是单击该元素,仅此而已

First of all pass value

首先传值

driver.findElement(By.xpath("//*[@id='sliderLocation']")).sendKeys("Knightsbridge")

Once it's done, it populate the values, So You need to click one of option, So you can directly click the element like this(since this population is taking time, you need to use implicit wait

完成后,它会填充值,因此您需要单击选项之一,因此您可以像这样直接单击元素(由于此填充需要时间,您需要使用隐式等待

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS))

And then write

然后写

driver.findElement(By.xpath("//a[text()='Knightsbridge, London']")).click()

Or if you want to choose the element which consist of Knightsbridgethen write the following code and this will choose the first option which consist of Knightsbridgethen write

或者,如果您想选择由Knightsbridge以下组成的元素,则编写以下代码,这将选择由以下组成的第一个选项,Knightsbridge然后编写

driver.findElement(By.xpath("//a[contains(text(),'Knightsbridge']")).click()

You don't have to use sleep statement anywhere in your selenium code, selenium automatically waits after the click until everything settle down properly. The one exceptional case is, If your page got refreshed after placing the value in your text box(Not necessary for select_list), then you need to use the implicit wait, otherwise even implicit wait is not necessary.

您不必在 selenium 代码的任何地方使用 sleep 语句,selenium 会在单击后自动等待,直到一切正常。一种例外情况是,如果您的页面在将值放入文本框中后刷新(select_list 不需要),那么您需要使用隐式等待,否则甚至不需要隐式等待。

The above code I converted from Ruby to Java, the original code which I used to check is from selenium Ruby binding, the code is below

上面的代码是我从Ruby转换成Java的,我用来检查的原始代码来自selenium Ruby binding,代码如下

@driver.find_element(:xpath, "//*[@id='sliderLocation']").send_keys "Knightsbridge"
@driver.manage.timeouts.implicit_wait = 10
@driver.find_element(:xpath, "//a[contains(text(),'Knightsbridge')]").click
@driver.find_element(:xpath, "//a[text()='Knightsbridge, London']").click

回答by Ranjeet

You can do as below:

您可以执行以下操作:

 String requiredCity = "London";
         List<WebElement> menu2 = driver.findElements(By.xpath("//ul[@id='ui-id-3']/li"));
         System.out.println("Total options: "+menu2.size());
         
         for(int i=0;i<menu2.size();i++)
         {
          String CurrentOption = menu2.get(i).getText();
          
          if(CurrentOption.contains(requiredCity)){
           System.out.println("Found the city : "+CurrentOption);
           menu2.get(i).click();
          }
         }

回答by Kevster

This is the full solution using Ranjeet's answer.

这是使用 Ranjeet 答案的完整解决方案。

           File file = new File("C:\Users\USER\Desktop\chromedriver.exe");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver();
    try {
        driver.get("http://www.Hymanson-stops.co.uk/");
        //begin the simulation
        WebElement menu = driver.findElement(By.xpath("//*[@id=\"sliderLocation\"]"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
        menu.sendKeys("London");
        Thread.sleep(4000);
        String requiredCity = "London";
        List<WebElement> menu2 = driver.findElements(By.xpath("//ul[@id='ui-id-3']/li"));
        System.out.println("Total options: " + menu2.size());

        for (int i = 0; i < menu2.size(); i++) {
            String CurrentOption = menu2.get(i).getText();

            if (CurrentOption.contains(requiredCity)) {
                System.out.println("Found the city : " + CurrentOption);
                menu2.get(i).click();
                Thread.sleep(6000);
                menu.sendKeys(Keys.RETURN);
            }
        }
        Thread.sleep(8000);
    } catch (Exception exp) {
        System.out.println("exception:" + exp);
        //close and quit windows
        driver.close();
        driver.quit();
    }
    //close and quit 
    driver.close();
    driver.quit();

回答by Andrea

WebElement selectMyElement = driver.findElement((By.xpath("//div/select/option[@value='Your value']")));
    selectMyElement.sendKeys("Your value");
    Actions keyDown = new Actions(myLauncher.getDriver());
    keyDown.sendKeys(Keys.chord(Keys.DOWN, Keys.DOWN)).perform();