1

With Selenium, I'm trying to find the following checkbox on webpage.

<input type="checkbox" value="1" onclick="             document.getElementById('lastCheminClicked').value='123';             createInputsBinaireCell(25,'colonne5',1,0789,1,1,0,this.checked, this);">

The distinctive part is the '123' value in the "onclick", this is what selenium should look for.

Any way to find it on page? I have tried with xpath with no sucess.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
n0tis
  • 750
  • 1
  • 6
  • 27
  • 4
    Why not use a xpath with `contains`, that should do the trick, I tried it in chrome on a test-website and it found the right element. What was wrong with your xpath?`$x("//input[contains(@onclick, \"value='123'\")]")` – MushyPeas Aug 08 '19 at 17:48

3 Answers3

2

As you mentioned the partial value 123 is distinct within the onclick event so to locate the element you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='checkbox'][onclick*='123']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@type='checkbox' and contains(@onclick,'123')]")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

You might try finding all input tags, and then iterate through each looking at the onclick attribute. For example:

from selenium.webdriver.common.by import By

input_tags = driver.find_elements(By.TAG_NAME, 'input')
found_tag = None
for input_tag in input_tags:
    onclick_attribute = input_tag.get_attribute('onclick')
    if ".value='123'" in onclick_attribute:
        found_tag = input_tag
        break

You'll probably need exception handling around the get_attribute call.

SeaChange
  • 161
  • 10
0

XPath selectors allow using contains() function which can be used for partial match on the attribute or text value of the DOM element.

The relevant selector would be something like:

//input[contains(@onlclick, '123')]

Demo:

enter image description here

More information:

Dmitri T
  • 159,985
  • 5
  • 83
  • 133