purelyawwesome
purelyawwesome

Reputation: 71

Select a checkbox with variables wih Selenium

The address below is the xpath address.

//label[@for="check54490"])

The check box is checked when typed as below.

driver.find_element_by_xpath('//label[@for="check54490"]').click()

However, there are many check boxes that need to be checked, so I am going to make variables and check them.

I made a variable as below, but an error occurs.

umber = [54490]
for num in umber:
    elem = f'//label[@for="check{num}"]'
    elm2 = f"'{elem}'"
    xpath = elem2
driver.find_element_by_xpath(xpath).click()

the error message is as follows.

Is the approach good or is it impossible in the first place?

Please give me some advice.

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression driver.find_element_by_xpath('//label[@for="check1000054759"]').click() because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string 'driver.find_element_by_xpath('//label[@for="check54490"]').click()' is not a valid XPath expression.
  (Session info: chrome=90.0.4430.85)

Upvotes: 2

Views: 67

Answers (1)

Dev
Dev

Reputation: 2813

Instead of doing it in for loop you can directly do it in the xpath for single value as below -

driver.find_element_by_xpath("//label[@for='check" + str(umber[0]) + "']")

Now since you have asked how you can do it in case of multiple values consider the following code example -

umber = [54490, 54490]
for num in umber:
    driver.find_element_by_xpath("//label[@for='check" + str(num) + "']").click()

OR you can have each number in different variable -

xbuttonNum = '54490'
ybuttonNum = '54491'
zbuttonNum = '54521' 

driver.find_element_by_xpath("//label[@for='check" + xbuttonNum + "']").click()
driver.find_element_by_xpath("//label[@for='check" + ybuttonNum + "']").click()
driver.find_element_by_xpath("//label[@for='check" + zbuttonNum + "']").click()

Alternatively you can customize your xpath unique for all the elements and iterate over them all at once like -

AllElementwithCheckString =  driver.find_elements_by_xpath("//label[starts-with(@for,'check')]")

for elem in AllElementwithCheckString:
    elem.click()

Upvotes: 1

Related Questions