I’m learning how to use Selenium with Python, and as a simple exercise I’m trying to click a button on a page. I’ve successfully located the button and clicked it, and I see the button physically get clicked, and the new page loads for a split second (I can see the URL path change) and then it reloads the page I was originally on. I don’t run any other code after the button click.
Why is this happening, and how can I fix it?
I tried clicking the button using each of .click() and execute_script(). I also tried adding a call to time.sleep() after the button click.
code:
driver.get("website")
driver.implicitly_wait(5)
driver.find_element(By.XPATH, "//label[text()='some text']").click()
l = driver.find_element(By.XPATH, "//button[text()='Search']")
driver.execute_script("arguments[0].click();", l);
2
Answers
This behavior might be due to JavaScript on the page or some other event handler interfering with the navigation. Here are some things you can try:
Instead of using implicitly_wait, use WebDriverWait along with ExpectedConditions to wait for the desired element to be clickable:
or After clicking the button, wait for the URL to change or for an element to be present on the new page:
The problem is with the site. You click "Search All" and the page refreshes but does nothing. There are some other weird things here as well where elements are available but if you click them too early, it doesn’t register.
Steps:
NOTE: date is set last because it opens a date picker that covers half the page. Setting the date last is simpler than having to deal with the date picker directly to have it close
Now the search results page displays.
Anyway, the code below is working.