简体   繁体   English

如何使用 Selenium 单击后代 li 元素?

[英]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.我正在使用 selenium 进行自动化并达到一个点,我单击一个下拉菜单,有 3 个选项,它们在 ul 列表中,每个选项都是一个 li 角色。 I am able to locate them and selenium can see them but selenium cannot click on them, it says it is not interactable.我能够找到它们并且 selenium 可以看到它们,但 selenium 无法单击它们,它说它不可交互。

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) (通常我对所有东西都使用 XPATH,但我想我会尝试 CSS Selector)

Here is the HTML code这是HTML代码

<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.我希望能够选择显示所有事件和跟踪。

From your code trials as per the value of the id attribute ie ext4-ext-gen1136 it seems the element is a dynamic element.根据id属性(即ext4-ext-gen1136)的值,从您的代码试验来看,该元素似乎是一个动态元素。


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 :要单击带有文本的<li>元素作为显示所有事件,您需要为element_to_be_clickable()诱导WebDriverWait ,并且可以使用以下任一定位器策略

  • Using CSS_SELECTOR :使用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 :使用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

我想通了,我必须打开下拉菜单才能单击它们,但是当 selenium 单击它时下拉菜单会立即关闭,我所要做的就是让 selenium 单击它两次,从而解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM