Björn Kristinsson
Björn Kristinsson

Reputation: 624

Getting Firefox to wait for new page to load after clicking a link in Selenium?

I'm just starting out with Selenium and wrote a bunch of tests using Chrome. I then tried running the same tests with Firefox, but most of them are failing.

I've a bunch of tests that are a bit like this:

1. Find link
2. Click link
3. Confirm the title of the new page matches what I expect

This works fine in Chrome, but in Firefox step 3 seems to be executed immediately, before the browser has had time to load the page. All tests pass if I add a wait of a couple of seconds, but I'd rather avoid that.

Is this a configuration issue, or is there a better way to write the tests to help with compatibility?

These are the basics of a test that works in Chrome, but fails in Firefox

link = driver.find_element_by_link_text(link_text)
link.click()
# Check if `driver.title` contains `title`
assert title in driver.title

Inserting a time.sleep(2) after the click does make it work.

(I get the same sort of error with my authentication test: fill in form, click submit, confirm user is forwarded to the right page. In Chrome, this passes, in Firefox the forward check is done against the login page since the browser still hasn't finished redirecting to the new page. I get the report that the tests failed, and a second later the browser renders the expected page.)

Upvotes: 2

Views: 427

Answers (1)

Andersson
Andersson

Reputation: 52665

You can apply following:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

current_title = driver.title # get current title
link = driver.find_element_by_link_text(link_text)
link.click()
wait(driver, 10).until(lambda driver: driver.title != current_title) # wait for title to be different than current one
assert title in driver.title

Upvotes: 2

Related Questions