'How to click on a descendant li element with Selenium?
I am automating with selenium and reached a point where I click a drop down and there are 3 options and they are in a ul list, and each option is an li role. I am able to locate them and selenium can see them but selenium cannot click on them, it says it is not interactable.
Here is the code that is interacting with it.
browser.find_element(by=By.XPATH, value='//*[@id="ext4-ext-gen1136"]').click()
browser.find_element(by=By.CSS_SELECTOR, value='#boundlist-1078-listEl > ul > li:nth-child(3)').click()
(normally I use XPATH for everything but I figured I would try CSS Selector)
Here is the HTML code
<ul class="x4-list-plain"><li role="option" unselectable="on" class="x4-boundlist-item x4-boundlist-selected">Show Latest Event</li><li role="option" unselectable="on" class="x4-boundlist-item">Show All Events and Traces</li><li role="option" unselectable="on" class="x4-boundlist-item">Show All Events</li></ul>
<li role="option" unselectable="on" class="x4-boundlist-item x4-boundlist-selected">Show
Latest Event</li>
<li role="option" unselectable="on" class="x4-boundlist-item">Show All Events and
Traces</li>
<li role="option" unselectable="on" class="x4-boundlist-item">Show All Events</li>
I want to be able to select show all events and traces.
Solution 1:[1]
I figured it out, I had to have the drop down open to click on them but the dropdown would immediately close when selenium clicked on it, all I had to do was make selenium click on it twice and that fixed the issue.
Solution 2:[2]
From your code trials as per the value of the id
attribute i.e. ext4-ext-gen1136 it seems the element is a dynamic element.
To click on the <li>
element with text as Show All Events you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.x4-list-plain li:nth-child(3)"))).click()
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='x4-list-plain']//li[@class='x4-boundlist-item' and text()='Show All Events']"))).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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DDUffy |
Solution 2 | undetected Selenium |