2017-07-07 65 views
0

調用一個方法,我有這樣的代碼:自動在一個類實例化

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: 
      return 'Logged in successfully' 
     else: 
      return soup.find('div', {'id' : 'errormessage'}).text 

我想log_in方法來自動運行,當我創建一個類的實例,例如:

print Alluris('username', 'password') 

輸出應該是:

Logged in successfully 

或者

Incorrect username or password 

基本上我並不想手動運行log_in方法類似

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

編輯:我試圖把self.log_in()__init__方法,但它只是返回類對象。

+0

你可以簡單地把你的'__init__'方法'self.log_in()'調用。 – taras

+0

@taras我試過了,但是隻返回類對象。 –

+1

如果您希望返回其他內容,您將如何獲得該課程的實例? –

回答

3

你可以做,通過調用方法在__init__方法:

class Alluris(object): 

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

我試過但它只返回類對象。 –

+2

@ V.Anh你可能應該在你的'log_in'中'print'不''return' –

+0

它的工作原理,非常感謝你,但是有沒有任何裝飾器允許我執行相同的事情? –