How do I access and click on a button which hyperlinks to a javascript function?
html element:
<a href="javascript:Nav('-index=')" id="ctl04_ctl25_ctl00_lnk2NextPg" role="button" onclick="mySpud.container.scrollIntoView();" title="Next Page" aria-label="Next Page">►</a>
My current code:
next_button='//*[@id="ctl04_ctl06_ctl00_lnk2NextPg"]'
try:
element=WebDriverWait(driver,15).until(
EC.presence_of_element_located((By.XPATH,next_button))
)
element.click()
except:
driver.quit()
Selenium is unable to find the element and I've also tried using the find_element() function using various methods (by id etc) to no avail.
CodePudding user response:
The locator //*[@id="ctl04_ctl06_ctl00_lnk2NextPg"]
doesn't seem to be static.
Try this:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@aria-label='Next Page']"))).click()
If this doesn't work, then you can try this:
element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@aria-label='Next Page']")))
driver.execute_script("arguments[0].click();", element)
Alternate locator:
You can use //*[@title= 'Next Page']
instead of @aria-label
locator
Alternate locator:
CodePudding user response:
You have to take care of a couple of things here:
The initial part of the value of the
id
attribute is dynamic as inctl04_ctl25_ctl00_lnk2NextPg
and it would change everytime you access the page afresh. So you have to construct a dynamic locator strategyMoving ahead as you are invoking
click()
, instead ofpresence_of_element_located()
you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:Using
CSS_SELECTOR
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[id$='NextPg'][title='Next Page'][aria-label='Next Page']"))).click()
Using
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@id, 'NextPg')][@title='Next Page' and @aria-label='Next Page']"))).click()