Home > Mobile >  How to Click on Checkbox based on class in Selenium?
How to Click on Checkbox based on class in Selenium?

Time:12-11

see website code: enter image description here

There are multiple td class='timeslotCellNonPeak", and each of these td class has the 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], 
...

Within some of these td classes, I have a checkbox that I want to click. My ultimate goal is to define a td class to search in, say

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

then click the checkbox if it is present.

I have tried looking for boxes with

id=gwt-uid-102

but that won't work as the id is different everytime.

In short I want to:

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.

CodePudding user response:

You can try something like this "Code not tested":

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

CodePudding user response:

To identify whether checkboxes present in a table cell for a specific row you can use the following xpath to identify that and then iterate and click.

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