Search code examples
pythonseleniumclassselenium-webdriverpython-class

Selenium program execution does not start using Python Class


Here is the code

class InstogramBot():

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Chrome()
    def close_browser(self):
        self.driver.get("https://www.instagram.com/")
        time.sleep(5)
        name_input = self.driver.find_element_by_name("username")
        name_input.send_keys(username)
        time.sleep(2)
        password_input = self.driver.find_element_by_name("password")
        password_input.send_keys(password)
        time.sleep(2)
        self.driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button/div').click()
        time.sleep(7)
        self.driver.close()
        self.driver.quit()

Selenium doesn't show up and doesn't even open the web driver

Console snapshot:

enter image description here


Solution

  • While using Python you need to consider the following:

    • Python being an object oriented programming language, everything in Python is represented as an object along with its properties and methods.
    • A Class in Python is the object constructor i.e. the mechanism for creating the objects.

    Your program

    The code block you have written includes the definition of the Class and the only method.

    To initiate a successful execution, you need to create an instance, i.e an object of the class InstogramBot()

    bot = InstogramBot("Рома", "Рома")
    

    Finally, you need to invoke the method close_browser() through the object.

    bot.close_browser()
    

    Solution

    Your effective code block will be:

    from selenium import webdriver
    
    class InstogramBot():
    
        def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Chrome()
    
        def close_browser(self):
        self.driver.get("https://www.instagram.com/")
        time.sleep(5)
        name_input = self.driver.find_element_by_name("username")
        name_input.send_keys(username)
        time.sleep(2)
        password_input = self.driver.find_element_by_name("password")
        password_input.send_keys(password)
        time.sleep(2)
        self.driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button/div').click()
    
    
    bot = InstogramBot("Рома", "Рома")
    bot.close_browser()