Невозможно вызвать щелчок по элементам UL Li в селене - PullRequest
0 голосов
/ 13 января 2019

Я использую селен-java и драйвер chrome для выбора элементов из списка UL. Я пытаюсь выбрать пункт "Сирса", но ничего не происходит. Структура списка UL похожа на приведенную ниже:

<div class="serachDept" id="names_department"><span class="departmentText">Mumbai</span>
    <ul class="serachDeptOptionList" style="overflow-y: scroll;">
        <li class="serachDeptOptionListElement"><span data-filter-value="Ratia"
                                                    class="srSearchOptionListElementText">Ratia</span></li>
        <li class="serachDeptOptionListElement"><span data-filter-value="Sirsa"
                                                      class="srSearchOptionListElementText">Sirsa</span></li>

        </li>
    </ul>
</div>

Я выбрал элементы, используя код Java:

 WebElement namesList = Hooks.driver.findElement(By.xpath("//*[@id='names_department']//ul"));
    List<WebElement> options = namesList.findElements(By.tagName("li"));
    for (WebElement option : options) {
        option.findElement(By.tagName("Span")).click();  // throws exception
    }
    options.get(2).click();//throws exception

Исключение:

Command duration or timeout: 0 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: '', ip: '', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_102'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.45.615291 (ec3682e3c9061c..., userDataDir: C:\Users\HP\AppData\Local\T...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: l}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 71.0.3578.98, webStorageEnabled: true}
Session ID: f68d79a1f74f3dc99c15d8a5f3104789
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
  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:80)
  at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
  at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
  at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
  at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
  at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
  at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
  at com.sg.game.steps_def.CareerMenuItemCheck.dropdown_Weblist_is_enabled_and_Clickable(CareerMenuItemCheck.java:253)

Может кто-нибудь помочь мне решить эту проблему?

Ответы [ 3 ]

0 голосов
/ 15 января 2019

Попробуйте это:

    List<WebElement> elements = 
    Hooks.driver.findElements(By.xpath("/*@id='names_department']//ul/li"));
    for (int i=0; i<elements.size(); i++) {
        if (elements.get(i).getTagName().equals("span") {
        elements.get(i).click()
        }       
    }
    elements.get(2).click();
0 голосов
/ 17 января 2019

Выше код выглядит глючно. Вам нужно разорвать петлю:

WebElement namesList = Hooks.driver.findElement(By.xpath("//*[@id='names_department']//ul"));
List<WebElement> options = namesList.findElements(By.tagName("li"));
for (WebElement option : options) {
    option.findElement(By.tagName("Span")).click();
    break;
}
//options.get(2).click();//throws exception

Или что-то вроде ниже.

WebElement namesList = Hooks.driver.findElement(By.xpath("//*[@id='names_department']//ul"));
List<WebElement> options = namesList.findElements(By.tagName("li"));
for (WebElement option : options) {
   if("Sirsa".equalsIgnoringCase(option.getText())){
      option.click(); 
      //option.findElement(By.tagName("Span")).click();
      break;
   }
 }   

Выше кода, по крайней мере, не выбрасывать исключение времени ожидания команды. И если вы обнаружили, что щелчок не вступает в силу, то вы можете использовать альтернативу запуска клика с использованием JavaScript.

Чтобы справиться с такими случаями, один из хорошо известных фреймворков с открытым исходным кодом QAF предоставляет функцию под названием пользовательский компонент . Используя это, вы можете создать свою собственную реализацию для webelement.

0 голосов
/ 14 января 2019

Решение - использовать JavascriptExecutor

JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", options.get(2));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...