无法使用Selenium Python选择无序列表中的列表项 [英] Not able to select a list item in an unordered list using selenium python

查看:109
本文介绍了无法使用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 is a variable containing the unordered list. os_version contains some text. say os_version = "KK"

一旦您开始遍历无序列表中的列表项,我们需要选中匹配项复选框.

Once you start traversing through the list items in an unordered list we need to select the matched item checkbox.

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

Use the following Xpath option to click on input checkbox whose label text is KK

os_version = "KK"
driver.find_element_by_xpath("//div[@class='ms-drop bottom']//ul//li[.//span[normalize-space(text())='"+ os_version + "']]//input").click()


或者您可以诱导WebDriverWaitelement_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()

您需要导入以下内容以执行上述代码.

You need to import followings to execute above code.

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

这篇关于无法使用Selenium Python选择无序列表中的列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆