May 12

Selenium – Select drop down option by Frontend Text

one of the annoying things i found in Selenium is that when working with a drop down you needed to know the value of the open you wanted to select which oftern is different from the value the user will see. if you was testing and you wanted to make sure that a front end user’s selection was correct for an dynamically-generated drop down selecting by value is pointless.

that is where this function comes in

public function selectOptByTxt($selectID,$txt)
    $selectExplode = explode('=',$selectID);
    if(count($selectExplode) < 2)
        $selectExplode = array('id',$selectExplode[0]);
    $this->logStr('Selecting "'.$txt.'" from Select List "'.$selectExplode[1].'" (locate by "'.$selectExplode[0].'")');
    $vals = $this->driver->executeScript("var options = document.querySelectorAll('select[".$selectExplode[0]."=\"".$selectExplode[1]."\"] option')
var rerurnArr = \"a:\"+options.length+\":{\"
for(i=0;i < options.length;i++)
rerurnArr += 's:'+options[i].text.length+':\"'+options[i].text+'\";s:'+options[i].value.length+':\"'+options[i].value+'\";'
rerurnArr += \"}\"
return rerurnArr");

    $vals = unserialize($vals);
    $selected = $vals[$txt];
    $select = new WebDriverSelect($this->driver->findElements(WebDriverBy::xpath("//select[@".$selectExplode[0]."='".$selectExplode[1]."']"))[0]);

the first argument $selectID work by checking the selector. if it’s just the id we don’t need to pass something like “id=myNode” but if it’s a class you would. also if you id or class is named like class="myCSSClass=AWSOMENESS" i am going to hit you. since when are we taught that any sort of identifier, unique or not, as anything other than letters, numbers, dashs and underscores.

now with out identifier we use it as apart of a CSS Selector in javascript to generate a serialized associative array containing the front facing text the user sees as keys and the background value the page submits as the values. we then unseralize the array so now when we select based off the text it’ll be matched to the value from the array. after this we use our selector to get the select element object that Selenium wants and use the value we found.

I suspect this will of cause fall over if the drop down has duplicate text values, never tested it myself. in that case i wouldn’t want to fix it because if the user is presented with 2 identical options how are they supposed to know the difference between them?

this code ofcuase assumes your using the code bellow in a class to create the RemoteWebDriver

$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::chrome();
$options = new ChromeOptions();
$capabilities->setCapability(ChromeOptions::CAPABILITY, $options);

$this->driver = RemoteWebDriver::create($host, $capabilities,86400000,86400000);

Leave a Reply

Your email address will not be published.