Home > Mobile >  How to identify a dynamic input checkbox element through xpath using Selenium
How to identify a dynamic input checkbox element through xpath using Selenium

Time:12-11

Hello I need some help i'm using python last version with selenium. I can't reach an element input checkbox. Here is the input :

<div >
  <input type="checkbox" name="yachi13" id="yachi13"  value="13">
</div>

I tried this :

# try 1
swClick(driver, 'xpath', "[//*@id='yachi"   teethValue   "']")
# try 2
driver.find_element_by_id("yachi"   teethValue)
# try 3
swClick(driver, 'xpath', "[//input[@name='yachi"   teethValue   "']")
# try 4
swClick(driver, 'xpath', "//div[@class='info info"   teethValue   " canClick']/input[@id='yachi"   teethValue   "']")
# try 5
swClick(driver, 'xpath', "//div[@class='info info"   teethValue   "']")
# try 6
for i in range(10):
  try:
      driver.find_element_by_xpath(
      "//input[@id='yachi"   teethValue   "']"
      ).click()
      break
  except NoSuchElementException as e:
      print('Retry in 1 second')
      time.sleep(1)
  else:
      raise e

The teethvalue is a number, and the swClick a function and work perfecly . Can you show me how to handle the checkbox with a classic way ? Thank you !

CodePudding user response:

You can use Literal String Interpolation also known as f-string Formatting as follows:

teethValue = "13"
print(f"//input[@name='yachi{teethValue}']")

Output:

//input[@name='yachi13']

Effectively, your code block will be:

# teethValue = "13"
driver.find_element(By.XPATH, f"//input[@name='yachi{teethValue}']").click()
  • Related