0

Assuming there is a page with buttons that have onclick events of the form:

<a onclick="doSomething($id)"></a>

The ids are permanent but sometimes the link is not yet loaded, or already stale and you would need to reload them.

Is it possible to trigger an onclick event in Selenium without getting the webelement and click(), or change the id for the onclick event of an existing webelement?

Edit: Most promising at the moment is to use javascript:

wd.execute_script("document.getElementById('what').onclick = function () { dosmth($id); };")

But this doesn't change the id visibly in the chrome element inspector, also the link does nothing anymore. Do I have an error in my js syntax? Also when I manually change the id in chrome element inspector it works just fine.

This did the trick for me:

self.execute_script("document.getElementById('what').setAttribute('onclick', 'dosmth($id)');")

1 Answers1

0

If you know the id of this element, you may wait for the element with "doSomething(known_id) onclick attribute value to be clickable:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

known_id = "id_I_know"
wait = WebDriverWait(driver, 10)
link = wait.until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[onclick="doSomething(%s)"]' % known_id))
)
link.click()

You can also make the click "via javascript":

driver.execute_script("arguments[0].click()", link)

See also:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195