1

I am using the following code to submit a form using Python. When the value entered is correct, it redirects to a new page called http://localhost/a/my.php. How do i check whether the page is redirected using python so that I can know that the values entered where correct.

from selenium import webdriver

webpage = r"http://localhost/a/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
for i in range(10):
    searchterm = i # edit me
    driver.get(webpage)
    sbox = driver.find_element_by_class_name("txtSearch")
    sbox.send_keys(searchterm)

    submit = driver.find_element_by_class_name("sbtSearch")
    submit.click()
1
  • You could use the driver.current_url to confirm it is the address you are looking for. If it does not work, maybe you have to wait for a page load, just add a time.sleep(x) or something. Commented Nov 17, 2017 at 9:14

3 Answers 3

1

locate an element that only exists after the new DOM is loaded. If you can find it, you are on the new page.

try:
    driver.find_element_by_class_name("txtSearch")
    print("redirected to new page")
except NoSuchElementException:
    print("oops, no redirect happened")
Sign up to request clarification or add additional context in comments.

4 Comments

If navigation to new page failed el = driver.find_element_by_class_name("txtSearch") should give you NoSuchElementException
Downvote?? May i know why?
I've already clarified. Your first approach is not efficient as script should break with exception if new page is not opened
just edited to catch NoSuchElementException instead of using is_displayed().
0

Try using current_url:

driver.current_url

Comments

0

to check whether the page is redirected properly or not, use a WebDriverWait (aka "explicit wait") with proper expected_conditions clause set to one of the following:

Python :

  1. url_to_be :

    WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))
    
  2. url_matches :

    WebDriverWait(driver, 10).until(EC.url_matches("https://www.google.co.in/"))
    
  3. url_contains :

    WebDriverWait(driver, 10).until(EC.url_contains("google"))
    
  4. url_changes :

    WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))
    

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.