selenium - 无法使用 selenium python 在无序列表中选择列表项
问题描述
I need to select a list item in an unordered list using selenium python.
HTML:
<div class="ms-drop bottom" style="display: block;">
<ul style="max-height: 400px;">
<li class="ms-select-all">
<label><input type="checkbox" data-name="selectAlls_osVer">
[Select all]
</label>
</li>
<li class="" style="false">
<label class=""><input type="checkbox" data-name="selectItems_osVer" value="KK">
<span style="">
KK
</span>
</label>
</li>
<li class="" style="false">
<label class=""><input type="checkbox" data-name="selectItems_osVer" value="KK_MR1">
<span style="">
KK_MR1
</span>
</label>
</li>
<li class="" style="false">
<label class=""><input type="checkbox" data-name="selectItems_osVer" value="KK_MR2">
<span style="">
KK_MR2
</span>
</label>
</li>
</ul>
</div>
Tried code:
unordered_list 是一个包含无序列表的变量。os_version 包含一些文本。说 os_version = "KK"
一旦您开始遍历无序列表中的列表项,我们需要选中匹配项复选框。
unordered_list = driver.find_element_by_xpath("//*[@id='fixedHeadSearch']/td[7]/div/div/ul")
list_items = unordered_list.find_elements_by_tag_name("li")
for list_item in list_items:
print(list_item.text)
if list_item.text == os_version:
list_item.click()
Expected:if text matches with list item perform click on it.
Actual:Not able to click on required list item.
解决方案
使用以下Xpath
选项单击标签文本为的输入复选框KK
os_version = "KK"
driver.find_element_by_xpath("//div[@class='ms-drop bottom']//ul//li[.//span[normalize-space(text())='"+ os_version + "']]//input").click()
或者你可以诱导WebDriverWait
和element_to_be_clickable()
os_version = "KK"
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='ms-drop bottom']//ul//li[.//span[normalize-space(text())='"+ os_version + "']]//input"))).click()
您需要导入以下内容才能执行上述代码。
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
推荐阅读
- c# - C#如何计算两个点之间的直角和等距的点
- google-chrome-extension - 私人托管的 chrome 扩展
- javascript - 谷歌云抛出错误:无法在 Nodejs 中加载默认凭据
- typescript - 打字稿将null分配给接口
- mysql - MYSQL:在这种情况下如何选择特定行?
- xamarin - 在三星 Tizen 5.5 电视模拟器上调试 Tizen .NET 应用程序时出现问题
- c# - Vlc.dotnet.form 用按钮暂停视频
- swagger - 如何修复 java.lang.RuntimeException:缺少招摇输入或配置?
- php - 除某些 WooCommerce 产品类别外,自动将产品添加到购物车
- wso2 - WSO2 APIM 2.2.0 如何从 API 商店中删除选项卡 - API 视图