简体   繁体   English

无法在Java Selenium中选择Bootstrap下拉列表

[英]Unable to select Bootstrap dropdown in Java Selenium

I'm having a very difficult time selecting bootstrap dropdown in Selenium. 我在Selenium选择bootstrap下拉时非常困难。

I'm new to Selenium so any suggestion and guidance would be very helpful, as what I'd love to do is just select the dropdown, type "email", and press enter during the instance. 我是Selenium的新手,所以任何建议和指导都会非常有用,因为我喜欢做的只是选择下拉列表,输入“email”,然后在实例中按Enter键。

I've gone through dozens of solutions, but none of them have worked for this specific issue. 我已经完成了几十个解决方案,但没有一个能够解决这个问题。

What can I do? 我能做什么? Please help. 请帮忙。

Salenium Salenium

 package newPackage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class importLeads { public static void main(String args[]) throws Exception { System.setProperty("webdriver.chrome.driver", "C:\\\\Users\\\\David\\\\Downloads\\\\Notes\\\\WebDriver\\\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //login to site driver.get("https://demos5.softaculous.com/Mautic/s/contacts/import/new"); driver.manage().window().maximize(); driver.findElement(By.id("username")).sendKeys("admin"); driver.findElement(By.id("password")).sendKeys("password"); driver.findElement(By.className("btn")).click(); Thread.sleep(2000); //importing Data WebElement uploadBox = driver.findElement(By.id("lead_import_file")); uploadBox.sendKeys("C:\\\\Users\\\\David\\\\Downloads\\\\data_file.csv"); driver.findElement(By.id("lead_import_start")).click(); //Select from dropdown WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')")); Actions cursor = new Actions(driver); cursor.moveToElement(dropdownToggle); cursor.click(); cursor.perform(); Thread.sleep(1000); WebElement weh = driver.findElement(By.id("lead_field_import_email_address_chosen")); Actions cursor2 = new Actions(driver); cursor2.moveToElement(weh); cursor2.click(); } } 


Here is the link to the data file ufile.io/vy2ws 这是数据文件ufile.io/vy2ws的链接

In order for the upload of the .CSV file to work, you must be running a local version of this software. 要使.CSV文件上载起作用,您必须运行此软件的本地版本。 Download can be found here: https://www.mautic.org/m/asset/54:mautic-2100 可以在此处找到下载: https//www.mautic.org/m/asset/54mautic-2100

Once uploaded, it should look like this where it asks to choose from the drop-down. 上传后,它应该看起来像是要求从下拉列表中选择。

在此输入图像描述

HTML HTML

 <div class="col-sm-4"> <div class="row"> <div class="form-group col-xs-12 "> <label class="control-label" for="lead_field_import_email_address">Email address</label> <div class="choice-wrapper"> <select id="lead_field_import_email_address" name="lead_field_import[email_address]" class="form-control" autocomplete="false" style="display: none;"> <option value=""></option> <optgroup label="Contact"> <option value="email">Email</option> </optgroup> </select> <div class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="width: 100%;" title="" id="lead_field_import_email_address_chosen"> <a class="chosen-single chosen-default"> <span>Choose one...</span> <div><b></b></div> </a> <div class="chosen-drop"> <div class="chosen-search"><input type="text" autocomplete="off"></div> <ul class="chosen-results"> <li class="group-result">Contact</li> <li class="active-result group-option" data-option-array-index="9" style="">Email</li> </ul> </div> </div> </div> </div> </div> </div> 


Replacing : 更换:

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_add‌​ress')")); 

to this : 对此:

WebElement dropdownToggle = driver.findElement(By.id("lead_field_import_email_address"))‌​;

resulted in: 导致:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 35535
Only local connections are allowed.
Oct 22, 2017 1:20:49 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"lead_field_import_email_address"}
  (Session info: chrome=61.0.3163.100)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'DAVID-PC', ip: '192.235.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\David\AppData\Local\Temp\scoped_dir4068_28713}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: ee90469095e7b1121dc2e387d8e485e6
*** Element info: {Using=id, value=lead_field_import_email_address}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:402)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
    at newPackage.importLeads.main(importLeads.java:31)

Replacing 更换

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));
    Actions cursor = new Actions(driver);

with

WebElement element =  driver.findElement(By.id("lead_field_import_email_address"));
    Select select = new Select(element);

resulted in: 导致:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 32443
Only local connections are allowed.
Oct 23, 2017 1:36:09 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"lead_field_import_email_address"}
  (Session info: chrome=61.0.3163.100)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'HOME-PC', ip: '192.235.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\David\AppData\Local\Temp\1\scoped_dir5416_25737}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: 40cde314a5a76400aceff8b625b38e3c
*** Element info: {Using=id, value=lead_field_import_email_address}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:402)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
    at newAutomation.importLeads.main(importLeads.java:33)

Looking at the HTML you have provided, the WebElement with id="lead_field_import_email_address" is with in a Select tag. 查看您提供的HTMLid="lead_field_import_email_address"WebElementSelect标签一起使用。 So instead of using Actions Class in this case we should try to use the Select Class instead as follows: 因此,在这种情况下,我们应该尝试使用Select Class,而不是使用Actions Class,如下所示:

WebElement element =  driver.findElement(By.id("lead_field_import_email_address"));
Select select = new Select(element);

Next, we can select any of the options by invoking either selectByIndex(n) , selectByValue("value") or selectByVisibleText("visible_text") method. 接下来,我们可以通过调用selectByIndex(n)selectByValue("value")selectByVisibleText("visible_text")方法来选择任何options

I tried to replicate manually the steps of your code but when I load the data_file.csv and I click the Upload button: 我尝试手动复制代码的步骤,但是当我加载data_file.csv并单击Upload按钮时:

在此输入图像描述

nothing happens. 什么都没发生。

And, in the html, there isn't the element that you try to find: 并且,在html中,没有您尝试查找的元素:

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));

That's why I wrote this comment . 这就是我写这篇评论的原因。

I can imagine that should open something. 我可以想象应该打开一些东西。 From the informations: 从信息:

  • Limit 限制
  • Delimiter 分隔符
  • Enclosure 附件
  • Escape 逃逸

I can suppose that you have to upload a file with a particular format. 我可以假设您必须上传具有特定格式的文件。

EDIT 编辑

Trying locally it works. 尝试在本地工作。 I don't understand well this part of your code: 我不太了解你的这部分代码:

        //Select from dropdown
        WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));
        Actions cursor = new Actions(driver);
        cursor.moveToElement(dropdownToggle);
        cursor.click();
        cursor.perform();
        Thread.sleep(1000);
        WebElement weh = driver.findElement(By.id("lead_field_import_email_address_chosen"));

        Actions cursor2 = new Actions(driver);
        cursor2.moveToElement(weh);
        cursor2.click();

If you want to choose from the email drop-down, you could use the xpath: 如果要从电子邮件下拉列表中进行选择,可以使用xpath:

WebElement we = driver.findElement(By.xpath("//div[@class='choice-wrapper']//div[@id='lead_field_import_email_address_chosen']"));

or simply the id: 或者只是id:

WebElement we= driver.findElement(By.id("lead_field_import_email_address_chosen"));

and execute the interested operation. 并执行感兴趣的操作。

So, for example: 所以,例如:

    WebElement we= driver.findElement(By.id("lead_field_import_email_address_chosen"));
    we.click();
    we.sendKeys("email");
    we.sendKeys(Keys.ENTER);

EDIT 2 编辑2

Your problem is that you use Thread.sleep(XXXX); 你的问题是你使用Thread.sleep(XXXX); in order to wait the elements. 为了等待元素。 This is not deterministic. 这不是确定性的。 You must use an explicit wait . 您必须使用明确的等待

From Explicit Waits : 显式等待

An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. 显式等待是您定义的代码,用于在进一步执行代码之前等待某个条件发生。 The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. 这种情况的极端情况是time.sleep(),它将条件设置为等待的确切时间段。 There are some convenience methods provided that help you write code that will wait only as long as required. 提供了一些便捷方法,可帮助您编写仅在需要时等待的代码。 WebDriverWait in combination with ExpectedCondition is one way this can be accomplished. WebDriverWait与ExpectedCondition相结合是一种可以实现的方法。

So, in java you need: 所以,在java中你需要:

WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));

Always from the previous link: 始终从上一个链接:

This waits up to 15 seconds before throwing a TimeoutException unless it finds the element to return within 15 seconds. 这会在抛出TimeoutException之前等待最多15秒,除非它发现元素在15秒内返回。 WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. 默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到它成功返回。 A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types. 对于所有其他ExpectedCondition类型,ExpectedCondition类型的布尔返回true或非null返回值成功返回。

Finally, the entire code: 最后,整个代码:

        String geckoDriver = System.getProperty("pathTo/geckodriver";
        System.setProperty("webdriver.gecko.driver", geckoDriver);
        WebDriver driver= new FirefoxDriver();
        driver.get("http://localhost:8888/2.10.0/s/contacts/import/new");
        driver.findElement(By.id("username")).sendKeys("admin");
        driver.findElement(By.id("password")).sendKeys("password");
        driver.findElement(By.className("btn")).click();

        WebDriverWait wait = new WebDriverWait(driver, 15);

        WebElement uploadBox=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_import_file")));
        uploadBox.sendKeys("/pathTo/data_file.csv");
        driver.findElement(By.id("lead_import_start")).click();

        //Select from dropdown
        WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));
        we.click();
        we.sendKeys("email");
        we.sendKeys(Keys.ENTER);

EDIT 3 编辑3

With Firefox, the above code (in my tests) is ok. 使用Firefox,上面的代码(在我的测试中)是可以的。 I noticed that you use Chrome. 我注意到你使用的是Chrome。 With Chrome, I have this problem . 使用Chrome,我遇到了这个问题 The solution works for me: 解决方案适合我:

        //Select from dropdown
        WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));
        /*we.click();
        we.sendKeys("email");*/

        Actions actions = new Actions(driver);
        actions.moveToElement(we);
        actions.click();
        actions.sendKeys("email");
        actions.sendKeys(Keys.ENTER);
        actions.build().perform();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM