Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific element in webdriver containing text

What are some good ways to retrieve a specific element in WebDriver/Selenium2 based only on the text inside the element?

<div class="page">
  <ul id="list">
    <li>Apple</li>
    <li>Orange</li>
    <li>Banana</li>
    <li>Grape</li>
  </ul>
</div>

Essentially, I'd like to write something like this to retrieve the specific element:

@driver.find_element(:id, "list").find_element(:text, "Orange")

This is very similar to how I would use a selector when finding text inside a link (i.e. :link_text or :partial_link_text), but I would like to find elements by text inside normal, non-link elements.

Any suggestions? How do you deal with this issue? (In case you were wondering, I am using Ruby.)

like image 295
bbbco Avatar asked Dec 22 '22 00:12

bbbco


2 Answers

You could do that with xPath. Something like this for your example:

@driver.find_element(:id, "list").find_element(:xpath, './/*[contains(., "Orange")]')
like image 161
Andy Tinkham Avatar answered Dec 28 '22 11:12

Andy Tinkham


A couple years late, but I was just going to ask this question and answer it so other could find it...

I used a css selector to get all the li elements and then filtered the array based on the text:

@driver.find_elements(css: '#list > li').select {|el| el.text == 'Orange'}.first

You could then .click or .send_keys :return to select the option.

like image 26
erroric Avatar answered Dec 28 '22 11:12

erroric