【问题标题】:How to Click on Checkbox based on class in Selenium?如何根据 Selenium 中的类单击复选框?
【发布时间】:2022-01-15 08:29:11
【问题描述】:

查看网站代码:

有多个td class='timeslotCellNonPeak",每个td类都有xpath:

//*[@id="searchResultTable"]/table/tbody/tr[2]/td[3], 
//*[@id="searchResultTable"]/table/tbody/tr[2]/td[4],
//*[@id="searchResultTable"]/table/tbody/tr[2]/td[5], 
...

在其中一些 td 类中,我有一个要单击的复选框。我的最终目标是定义一个 td 类进行搜索,比如说

//*[@id="searchResultTable"]/table/tbody/tr[2]/td[3]

如果存在,请单击复选框。

我尝试过寻找带有

的盒子
id=gwt-uid-102

但这不起作用,因为 id 每次都不同。

总之我想:

i = # i will define a number here
tdClass = driver.find_element_by_xpath("//*[@id="searchResultTable"]/table/tbody/tr[2]/td[i]")

# then within this tdClass, click the checkbox if checkbox is present.

【问题讨论】:

    标签: python selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    您可以尝试这样的“代码未测试”:

    check_boxes =  driver.find_elements_by_class_name('timeslotCellNonPeak')
    for box in check_boxes:
        try:
             box.find_element_by_xpath('//input[@type="checkbox"]')
        except Exception as e:
             print('Checkbox not found')
    

    【讨论】:

    • 我不需要遍历所有框来检查复选框是否可用。我只想搜索我定义的特定内容。我该怎么做?
    • 刚试过你的答案,这段代码的问题是说框1有一个复选框,它可以成功点击复选框。但是,框 2 没有复选框,我认为搜索复选框会搜索所有框,并导致从框 1 中取消选中选中的复选框。
    • 复选框所在行是否有文本?您可以查找特定文本,找到它所在的行,然后单击同一行上的复选框。
    • 不,复选框上没有文字
    • 所以复选框之间的唯一区别是 id?
    【解决方案2】:

    要确定checkboxes 是否存在于特定行的表格单元格中,您可以使用以下xpath 来识别它,然后迭代并单击。

    checkboxes = driver.find_elements_by_xpath("//*[@id='searchResultTable']/table/tbody/tr[2]//td[.//input[@type='checkbox']]//input[@type='checkbox']")
    
    for chk in checkboxes:
       chk.click()
    

    【讨论】:

      【解决方案3】:

      假设您已决定这些索引可以是完全随机的。您可以使用 f 字符串来创建您的 xpath。然后尝试单击该元素。

      rows=[3,4,5]
      for row in rows:
          xpath=f"//*[@id='searchResultTable']/table/tbody/tr[2]/td[{row}]/span[1]/input[1]"
          print(xpath)
          try:
              driver.find_element_by_xpath(xpath).click()
          except:
              continue
      

      【讨论】:

        猜你喜欢
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        • 2022-11-20
        • 2021-08-10
        • 2017-09-24
        • 2021-12-11
        相关资源
        最近更新 更多