user3174886
user3174886

Reputation: 301

Search and compare string from ul li using python

I'm trying to search a string from the list using python (Selenium webdriver)

<li role="treeitem" aria-expanded="true" id="List" class="jstree-node  jstree-open">
   <i class="jstree-icon jstree-ocl"></i>
   <a class="jstree-anchor" href="#"><i class="jstree-icon jstree-themeicon"></i>Employees</a>
   <ul role="group" class="jstree-children">
      <li role="treeitem" id="workid:1" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl"></i>
         <a class="jstree-anchor" href="#"><i class="jstree-icon jstree-themeicon"></i>Anna Def(1)</a></li>
      <li role="treeitem" id="workid:2" class="jstree-node  jstree-leaf" aria-selected="false"><i class="jstree-icon jstree-ocl"></i>
          <a class="jstree-anchor" href="#"><i class="jstree-icon jstree-themeicon"></i>Dave Hjk(2)</a></li>
      <li role="treeitem" id="workid:3" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl"></i>
          <a class="jstree-anchor" href="#"><i class="jstree-icon jstree-themeicon"></i>Ght Dgh(3)</a></li>
       <li role="treeitem" id="workid:4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl"></i>
          <a class="jstree-anchor" href="#"><i class="jstree-icon jstree-themeicon"></i>Acdc Dedef(4)</a></li>

From this list I want to find the Employee Dave Hjk(2)from the tree and select him. How can I search using loop?

This is what I tried but I think the way I'm getting the array (li) is worng :(

  li = SeleniumHelperInstance.driver.find_elements_by_xpath("//*[@id="List"]/ul")


  for i in range(len(li)):
    selectuser = "Dave Hjk(2)"
    compUser = SeleniumHelperInstance.driver.find_element_by_css_selector("#List > ul > li:nth-child(i)")
    if (selectuser == compUser.text):
        compUser.click()

Upvotes: 1

Views: 106

Answers (1)

Florent B.
Florent B.

Reputation: 42518

You could first locate the tree and then the link with find_element_by_link_text :

driver.find_element_by_id("List") \
      .find_element_by_link_text("Dave Hjk(2)") \
      .click()

You could also use an XPath to get the the link with a single call:

driver.find_element_by_xpath("id('List')//a[.='Dave Hjk(2)']") \
      .click()    

Upvotes: 1

Related Questions