在selenium中使用类来避免冗余代码

时间:2018-02-27 11:38:48

标签: python-2.7 function class selenium selenium-webdriver

我必须打开2个网站,它们是相同的,所以我只需要更改URL,用户名并传递给登录,现在我有两个函数用相同的代码手动发送2个不同的用户和密码集。

我想使用A类,传递用户,传递和url到它并连接到一个网站,这是我到目前为止:

class Alienvault:

url = ''
alienuser = ''
alienpass = ''
def Conexion(self):

    driver = webdriver.Firefox()
    driver.implicitly_wait(10)
    driver.get(url)
    nombreusuario = driver.find_element_by_name('user')
    password = driver.find_element_by_name('passu')
    nombreusuario.clear()
    password.clear()
    nombreusuario.send_keys(alienuser)
    password.send_keys(alienpass)

    login = driver.find_element_by_id('submit_button')
    login.click()
    time.sleep(4)
    analisis = driver.find_element_by_id('li_analysis')
    analisis.click()
    eventos = driver.find_element_by_id('sm_opt_analysis-security_events')
    eventos.click()
    driver.maximize_window()

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

class Alienvault:

    def __init__(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(10)

    def login(self, user, password, url):
        self.driver.get(url)
        nombreusuario = self.driver.find_element_by_name('user')
        password = self.driver.find_element_by_name('passu')
        nombreusuario.clear()
        password.clear()
        nombreusuario.send_keys(user)
        password.send_keys(password)
        login = self.driver.find_element_by_id('submit_button')
        login.click()
        time.sleep(4)
        analisis = self.driver.find_element_by_id('li_analysis')
        analisis.click()
        eventos = self.driver.find_element_by_id('sm_opt_analysis-security_events')
        eventos.click()
        self.driver.maximize_window()

con = Alienvault()
con.login('myuser1', 'mypass1', 'www.myurl.com')
con.login('myuser2', 'mypass2', 'www.my_other_url.com')