Wait for Selenium WebDriver page redirection (Python)

I have a page that loads dynamic content using ajax and then redirects after a certain time (not fixed). How to make Selenium Webdriver wait for the page to redirect and then go to another link right after?

import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Chrome(); driver.get("http://www.website.com/wait.php") 
+5
source share
3 answers

You can create a custom Expected Condition to wait for a URL change:

 from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait wait = WebDriverWait(driver, 10) wait.until(lambda driver: driver.current_url != "http://www.website.com/wait.php") 

The expected condition can mainly be caused - you can wrap it in a class by overwriting the __call__() magic method when the built-in conditions are implemented.

+5
source

It’s good practice to β€œwait” for a unique element to appear (for a new page).

You can use the expected_conditions module.

For example, you can wait for the user logo to be entered:

 from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get('http://yourapp.url') timeout = 5 try: logo_present = EC.presence_of_element_located((By.ID, 'logo_id')) WebDriverWait(driver, timeout).until(logo_present) except TimeoutException: print "Timed out waiting for page to load" 
+3
source

There are several ExpectedConditions that you can use with ExplicitWait to redirect pages:

 from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) 
  • Wait for the new page title with title_is(title_name) :

     wait.until(EC.title_is('New page Title')) 
  • Wait for the current URL to be changed to any other URL with url_changes(exact_url) :

     wait.until(EC.url_changes('https://current_page.com')) 
  • Wait until you get to the exact url with url_to_be(exact_url) :

     wait.until(EC.url_to_be('https://new_page.com')) 

Also

url_contains(partial_url) can be used to wait for a URL that contains the specified substring, or url_matches(pattern) - wait for the URL associated with the regular expression pattern, or title_contains(substring) - wait for a new title that contains the specified substring

0
source

Source: https://habr.com/ru/post/1258091/


All Articles