phpselenium-webdriverjquery-select2

Solution for Unable to locate element based on text option of select on Selenium


I'm struggling to create auto click using PHP Selenium for select2 dropdown based on text name, instead of value option because the value is random.

HTML

<div class="input-group-prepend">
    <select name="target" id="target" class="form-control select2-hidden-accessible" data-select2-id="select2-data-acctarget" tabindex="-1" aria-hidden="true">
        <option value="" data-select2-id="select2-data-4-lu1l">-- Please Select --</option>
        <option value="hashrandom" data-select2-id="select2-data-5-i9za">Option1</option>
    </select>
    <span class="select2 select2-container select2-container--default" dir="ltr" data-select2-id="select2-data-3-0a3d" style="width: 360.312px;">
        <span class="selection">
            <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-acctarget-container">
                <span class="select2-selection__rendered" id="select2-acctarget-container" role="textbox" aria-readonly="true" title="-- Please Select --">-- Please Select --</span>
                <span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>
            </span>
        </span>
        <span class="dropdown-wrapper" aria-hidden="true"></span>
    </span>
    <button type="button" class="btn btn-link btn-sm" data-toggle="tooltip" data-placement="top" title="" data-original-title="tooltips_target"><i class="fa fa-question-circle"></i></button>
</div>

Code

if(!$this->wait('#target','visibilityOfElementLocated',5,500)) return $this->sendError('form not found');
if($this->executeScript("$('#target').click();"));
if(!$this->click('option[text=\'Option1\']')) return $this->sendError('select error.');

But got an error

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"option[text='Option1']"}

Solution

  • According to the docs, there is a WebDriverSelect class that you can use to make it easier to work with SELECT HTML elements.

    The code would look like

    $selectElement = $driver->findElement(WebDriverBy::id('target'));
    $select = new WebDriverSelect($selectElement);
    $select->selectByVisibleText('Option1');
    

    or

    $selectElement = $driver->findElement(WebDriverBy::id('target'));
    $select = new WebDriverSelect($selectElement);
    $select->selectByValue('hashrandom');