Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 612
ac2001 Avatar asked Jun 19 '16 14:06

ac2001


People also ask

What is an alternative option to driver get () method to open an URL?

You can use Java script, there is a command window. location='url' which can help you to achieve this.

Can Selenium interact with already opened browser?

New Selenium IDEWe can interact with an existing browser session. This is performed by using the Capabilities and ChromeOptions classes. The Capabilities class obtains the browser capabilities with the help of the getCapabilities method.


2 Answers

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()
like image 88
alecxe Avatar answered Sep 28 '22 14:09

alecxe


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"

like image 26
Hari Kiran K Avatar answered Sep 28 '22 13:09

Hari Kiran K