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

时间:2017-10-21 04:04:23

标签: java twitter-bootstrap selenium selenium-webdriver

我很难在Selenium中选择bootstrap下拉列表。

我是Selenium的新手,所以任何建议和指导都会非常有用,因为我喜欢做的只是选择下拉列表,输入“email”,然后在实例中按Enter键。

我已经完成了几十个解决方案,但没有一个解决过这个问题。

我该怎么办?请帮忙。

Salenium

pandas.append

以下是数据文件ufile.io/vy2ws

的链接

要使.CSV文件上传起作用,您必须运行此软件的本地版本。可在此处找到下载:https://www.mautic.org/m/asset/54:mautic-2100

上传后,它应该看起来像是要求从下拉列表中选择。

enter image description here

HTML

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

	}
}

更换:

<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>

到此:

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

导致:

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

更换

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)

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

导致:

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

2 个答案:

答案 0 :(得分:3)

查看您提供的HTML,带有WebElement id="lead_field_import_email_address" 位于 Select 中标签。因此,在这种情况下,我们应该尝试使用Actions类,而不是使用 Select 类,如下所示:

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

接下来,我们可以通过调用optionsselectByIndex(n)selectByValue("value")方法来选择selectByVisibleText("visible_text")中的任何一个。

答案 1 :(得分:3)

我尝试手动复制代码的步骤但是当我加载data_file.csv并点击上传按钮时:

enter image description here

没有任何反应。

而且,在html中,没有你试图找到的元素:

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

这就是我写this comment的原因。

我可以想象应该打开一些东西。来自信息:

  • 限制
  • 定界符
  • 机箱
  • 逃逸

我可以假设您必须上传具有特定格式的文件。

修改

尝试本地工作。 我不太了解你的这部分代码:

        //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();

如果要从电子邮件下拉列表中进行选择,可以使用xpath:

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

或只是id:

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

并执行感兴趣的操作。

所以,例如:

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

编辑2

您的问题是您使用 Thread.sleep(XXXX); 来等待元素。这不是确定性的。您必须使用显式等待

来自Explicit Waits

  

显式等待是您定义的等待某个条件的代码   在进一步执行代码之前发生。极端的情况   这是time.sleep(),它将条件设置为精确的时间段   等待。有一些方便的方法可以帮助您   编写只会在需要时等待的代码。 WebDriver等待   与ExpectedCondition的结合是一种可行的方式   来完成的。

所以,在java中你需要:

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

始终来自上一个链接:

  

在抛出TimeoutException之前等待最多15秒,除非   它找到要在15秒内返回的元素。 WebDriver等等   default每500毫秒调用一次ExpectedCondition,直到它   成功返回。成功的回报是针对ExpectedCondition   type is Boolean返回true或not null返回所有其他值的值   预期的条件类型。

最后,整个代码:

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

编辑3

使用Firefox,上面的代码(在我的测试中)是可以的。我注意到你使用的是Chrome。使用Chrome,我有this problemsolution对我有用:

        //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();