简体   繁体   中英

Python Selenium - Using same driver instance which is initiated in another file

In first file , there is a below code.

I want to use the driver instance of first file in second file , I am able to call it but getting an exception Nosuchelementexception

Basically i want the same browser session in both files , note that import statements are provided properly to use those.

class Init(): driver = webdriver.Chrome( executable_path="C:\\Program Files (x86)\\Python36-32\\selenium\\webdriver\\chromedriver_win32\\chromedriver.exe")

def take_screenshot(self):
    Init.driver.get_screenshot_as_png("Testcase.png")

def browser_launch(self):
    Init.driver.set_page_load_timeout(20)
    Init.driver.get("http://url/")
    Init.driver.maximize_window()

def user_comes_in(self):
    Init.driver.find_element_by_id("username").send_keys("admin")
    Init.driver.find_element_by_name("password").send_keys("admin")
    Init.driver.find_element_by_class_name("Button").click()
    Init.driver.set_page_load_timeout(20)

In second file , here is the code

initiate = Init()

class Two(unittest.TestCase): initiate.browser_launch()

def test_user_logs(self):
    initiate.user_comes_in()
    print("test case one")

def test_user_create(self):

    initiate.user_creation()
    print("Test case two")

if you can keep the browser open, you can do it like this:

init.py:

def setDriver():
    driver = webdriver.Firefox()
    driver.maximize_window()

driver = setDriver()

1.py:

from init.py import driver
driver.get('xxxx')

2.py:

from init.py import driver
driver.get('yyyy')

they will use same driver and same browser. but if you close the driver in any of the case file, others can't use it again. so it only available in cases don't need to close browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM