简体   繁体   中英

Python selenium driver instance not defined even though instance is returned by method

I am using Selenium in Python 3.7 with Firefox and the gecko driver. I have a method that calls another method to log into a site. The log in method creates a driver instance, logs in, and returns the driver instance. The original method is then supposed to proceed but I get an error 'driver' is not defined . I've done some research and near as I can tell, I'm doing everything right. Here is what I have, I just cut out a lot of the page navigating:

def navigate():
   login()
   driver.get("http://www.example.com")

def login():
   driver = webdriver.Firefox(executable_path="./geckodriver.exe")
   ...(login code here)
   return driver

When calling the navigate method, Firefox opens and logs in fine but when going to the example URL it says driver is not defined. I can't figure out what I am doing wrong. I'm not sure why it says driver is not defined.

EDIT: I just found out if I make driver global it will work but why doesn't it work by returning it? I don't necessarily need it to be global.

As you didn't post your code, it can only ever be a guess... however, it sounds like you're simply not assigning the returned object to your driver variable.

That issue is present in your incomplete code that you gave, it should look like:

def navigate():
   driver = login()
   driver.get("http://www.example.com")

def login():
   driver = webdriver.Firefox(executable_path="./geckodriver.exe")
   ...(login code here)
   return driver

The change here is that now driver is assigned the value of the returned login() object. It works when making driver a global because then the navigate() function has visibility of the driver object from login() .

Odd that you didn't get/notice a not defined error.

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