简体   繁体   English

如何在Python3中使用selenium驱动点击列表项

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

I have the following HTML code我有以下 HTML 代码

<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 .我需要单击列表项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.当我打印 turn_vmon 变量的文本时,我可以看到我需要的选项。 However I am unable to figure out how to click on the list item.但是我无法弄清楚如何单击列表项。

Can someone please help?有人可以帮忙吗?

To click on the element with text as Turn On you can use either of the following Locator Strategy :要单击带有文本作为打开的元素,您可以使用以下任一定位器策略

  • Using xpath :使用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 :理想情况下,单击您需要为element_to_be_clickable()诱导WebDriverWait的元素,您可以使用以下任一Locator Strategy

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

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

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