我有一个代码:
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 :(得分:3)
您可以通过调用__init__
方法中的方法来执行此操作:
class Alluris(object):
def __init__(self, username, password):
self.username = username
self.password = password
self.log_in()