ac2001
ac2001

Reputation: 736

Changing Selenium driver for new URL

I used Selenium to navigate to a URL (i.e. URL_1) with a login/password and provided the login credentials. I'm logged in and the URL (i.e. URL_2) has changed as expected. I don't know how to navigate URL_2 because the driver still refers to URL_1.

Thanks in advance.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

user_name = 'xyz'
password = 'xyz'

def login_process():
    driver = webdriver.Firefox()
    driver.get("URL_1") 
    #successfully navigated to URL_1

    elem = driver.find_element_by_name("username")
    elem.clear()
    elem.send_keys(user_name)

    elem = driver.find_element_by_name("password")
    elem.clear()
    elem.send_keys(password)
    driver.find_element_by_id("submit").click()
    #successfully entered URL_2 

def query():
    HOW DO I CHANGE THE DRIVER TO URL_2?

    #elem = driver.find_element_by_class_name(ticker_box) #this doesn't work, references URL_1 driver
    #elem.clear()
    #elem.send_keys('xyz')

Upvotes: 7

Views: 28089

Answers (3)

Hari Kiran K
Hari Kiran K

Reputation: 41

After navigating to the new page if you want to do something on that new page

newURl = driver.window_handles[0]

driver.switch_to.window(newURl)

After doing this you can do something in the new url without getting "no such element exceptions"

Upvotes: 2

Neekoy
Neekoy

Reputation: 2543

First you can assign the url variable as a global:

global url;
url = "firstURL"

At the end of your first function you can change the value of the variable to the new URL:

url = driver.current_url

And then you can get the new url at the beginning of your second function:

driver.get(url)

Upvotes: 0

alecxe
alecxe

Reputation: 474091

Instead of having independent functions, create a class with driver instance as an instance variable. Then, use self.driver.get() to navigate to a different URL:

class MyTest(object):
    def __init__(self):
        self.driver = webdriver.Firefox()

    def login_process(self):
        self.driver.get("URL_1") 
        #successfully navigated to URL_1

        elem = self.driver.find_element_by_name("username")
        elem.clear()
        elem.send_keys(user_name)

        elem = self.driver.find_element_by_name("password")
        elem.clear()
        elem.send_keys(password)
        self.driver.find_element_by_id("submit").click()
        #successfully entered URL_2 

    def query(self):
        self.driver.get("URL2")
        # do smth

test = MyTest()
test.login_process()
test.query()

Upvotes: 7

Related Questions