首页 > 解决方案 > 如何检查特定元素的复选框?

问题描述

无法选中属于特定图像的复选框。 https://i.stack.imgur.com/upIYA.png

def select_image_in_drawer(self, image_name):

    checkbox = self.driver.find_element(*EditSpecificationLocators.DRAWER_IMAGE_CHECKBOX)
    drawer_image = self.driver.find_elements(*EditSpecificationLocators.DRAWER_IMAGE_NAME)
    for iname in drawer_image:
        tag_val = iname.text # get text of an element
        if image_name == iname.text:
            print(tag_val)
            checkbox.click()

标签: pythonselenium

解决方案


您不会根据iname. 你总是点击checkbox。您应该能够使用下面的 XPath 定位器找到“kyoScan-4”的复选框

//div[@class='d-flex h-100 p-2'][.//div[.='kyoScan-4']]//span[@class='p-checkbox-icon p-c']
^ find a DIV
     ^ that contains this class
                                ^ that has a descendant DIV
                                       ^ that contains text kyoScan-4
                                                       ^ then find the descendant SPAN
                                                             ^ that has this class

使用该定位器(修改为查找image_name包含的文本),您可以将方法简化为单行

def select_image_in_drawer(self, image_name):
    self.driver.find_element_by_xpath("//div[@class='d-flex h-100 p-2'][.//div[.='" + image_name + "']]//span[@class='p-checkbox-icon p-c']").click()

注意:您可能需要等待元素可单击...然后单击它。


推荐阅读