Not able to select a list item in an unordered list using selenium python

▼魔方 西西 提交于 2020-01-25 03:56:08

问题


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 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.

回答1:


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()

Or You can induce WebDriverWait and 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()

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



回答2:


Try

driver.find_element_by_xpath("//*[@id='fixedHeadSearch']//ul/li[text()=" + os_version + "]").click()


来源:https://stackoverflow.com/questions/58507901/not-able-to-select-a-list-item-in-an-unordered-list-using-selenium-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!