V.Anh
V.Anh

Reputation: 535

Auto call a method upon instantiating a class

I have this code:

from selenium import webdriver
from bs4 import BeautifulSoup as BS
from types import NoneType 


class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def log_in(self):
        driver = 
webdriver.PhantomJS('C:\Users\V\Desktop\PY\web_scrape\phantomjs.exe')
        driver.get('https://alluris.han.nl')
        driver.find_element_by_id('username').send_keys(self.username)
        driver.find_element_by_id('password').send_keys(self.password)
        driver.find_element_by_xpath('//*
[@id="formfields"]/input[3]').click()
        soup = BS(driver.page_source, 'lxml')
        if type(soup.find('div', {'id' : 'errormessage'})) == NoneType:
            print 'Logged in successfully'
        else:
            print soup.find('div', {'id' : 'errormessage'}).text 

I want the log_in method to auto run when I create an instance of a class, for example:

Alluris('username', 'password')

Output should be: Logged in successfully or Incorrect username or password.

I don't want to run the log_in method manually like

 Alluris('username', 'password').log_in()

Upvotes: 0

Views: 1173

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can do that by calling the method in your __init__ method:

class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.log_in()

Upvotes: 3

Related Questions