Search code examples
pythonpython-3.xseleniumheadless-browser

Python how to pass selenium driver into function


I keep on getting this error when running my code:

**name 'driver' is not defined**

Can anybody tell me why? How would I make it run like this. So If any of the smaller tests fail, it is very clear where the problem is.

generateRandomBroswerInfo()
loginSite()
getSomeInfo()
quitBroswer()

I am using selenium on Python 3.6

My code:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def genrateBroswer():
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3')
    driver = webdriver.PhantomJS(desired_capabilities=dcap)
    driver.set_window_size(300, 600)

def letssee():
    driver.get('http://www.whatsmyip.org/')
    driver.save_screenshot('this.png')


genrateBroswer()
letssee()
#ETC

Solution

  • You could use a class with all the necessary methods, see Classes. An example:

    class Webdriver:
    
        def __init__(self):
            self.genrateBroswer()
            self.letssee()
    
    
        def genrateBroswer(self):
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3')
            self.driver = webdriver.PhantomJS(desired_capabilities=dcap)
            self.driver.set_window_size(300, 600)
    
        def letssee(self):
            self.driver.get('http://www.whatsmyip.org/')
            self.driver.save_screenshot('this.png')
    
    
    # Creating an instance of the webdriver
    myWebsite = Webdriver()
    
    myWebsite.driver
    

    In short, everything you need to use across functions, you need to make a property of the class by storing it with the keyword self, and you need to pass self to all the functions in the class.