Search code examples
pythonseleniumselenium-webdriverxpathwebdriverwait

How to click on the list item using selenium driver in Python3


I have the following HTML code

<ul id="vmStateDropDown" class="dropdown-content active" style="white-space: nowrap; position: absolute; top: 83px; left: 264px; opacity: 1; display: block;"><li class="waves-effect waves-default" style="display: block;"><a class="" style="cursor: pointer;"><i class="material-icons left" style="cursor: pointer;">directions_run</i><span>Turn On</span></a></li><li class="waves-effect waves-default" style="display: block;"><a class="disabled" disabled="" style="cursor: pointer;"><i class="material-icons left" style="cursor: pointer;">power_settings_new</i><span>Turn Off</span></a></li><li class="waves-effect waves-default" style="display: block;"><a class="disabled" disabled="" style="cursor: pointer;"><i class="material-icons left" style="cursor: pointer;">loop</i><span>Restart</span></a></li></ul>

I need to click in the list item Turn On. Here is the code I have so far.

turn_vmon = driver.find_elements(By.XPATH,'/html/body/div[4]/main/div/div[3]/div[3]/div[1]/ul/li[1]')

When I print the text for turn_vmon variable, I can see the option which I need. However I am unable to figure out how to click on the list item.

Can someone please help?


Solution

  • To click on the element with text as Turn On you can use either of the following Locator Strategy:

    • Using xpath:

      driver.find_element(By.XPATH, "//span[text()='Turn On']").click()
      

    Ideally to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategy:

    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Turn On']"))).click()
      
    • Note: You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC