L Pratama
L Pratama

Reputation: 39

How to obtain text from list of elements in Selenium Python?

Consider the following HTML code.

<div id="tree" style="max-height: 300px; overflow-y: scroll;" class="treeview">
 <ul class="list-group">
  <li class="list-group-item node-tree" data-nodeid="0" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Apples
  </li>
  <li class="list-group-item node-tree" data-nodeid="1" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Bananas
  </li>
  <li class="list-group-item node-tree" data-nodeid="2" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Mangoes
  </li>
  <li class="list-group-item node-tree" data-nodeid="3" style="color:undefined;background-color:undefined;">
   <span class="icon glyphicon"></span>
   <span class="icon node-icon glyphicon glyphicon-unchecked">
   </span>
   Grapes
  </li>
 </ul>
</div>

I tried to obtain the text "Apples", "Bananas", "Mangoes", and "Grapes" using

i = 1
m = 2
while i < m:
    css_id = ".list-group-item:nth-child(" + str(i) + ") > .node-icon"
    try:
        fruit_text = driver.find_element(By.CSS_SELECTOR, css_id).text
        print(fruit_text)
        i += 1
        m += 1
    except:
        i += 1

but resulting no strings were printed.

Any ideas to solve it?

Upvotes: 1

Views: 64

Answers (1)

cruisepandey
cruisepandey

Reputation: 29362

This should work for you :

fruits_list = driver.find_elements_by_css_selector('.list-group-item.node-tree')

for fruit in fruits_list:
   print(fruit.text)

Just make sure that .list-group-item.node-tree this css selector should indicates fruits on the web page.

Upvotes: 1

Related Questions