selenium 账号密码登录一个网站 需要加上等待元素出现的条件EC 很重要
# 导入包 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep # 登录商城 class login_shop(): def __init__(self,driver): self.driver=driver self.input_name=(By.ID,"username") self.input_psw=(By.ID,"password") self.login_button=(By.ID,"btnLogin") def login(self,name,psw): WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.input_name)).send_keys(name) WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.input_psw)).send_keys(psw) WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.login_button)).click() # self.driver.find_element(self.input_name).send_keys(name) # self.driver.find_element(self.input_psw).send_keys(psw) # self.driver.find_element(self.login_button).click() # 退出 def quit(self): self.quit() # 实例化调用登录商城类 if __name__ == '__main__': # 实例化webdirver driver = webdriver.Chrome() # 打开浏览器 driver.get("http://XXX:38090/#/login") # 将driver传给类,实例化一个对象l l=login_shop(driver) # l 调用方法 l.login(name='朝天宫383',psw='123456') sleep(2) l.quit()
xpath 使用练习
# 导入包 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep # 登录商城 class login_shop(): def __init__(self,driver): self.driver=driver self.input_name=(By.XPATH,"//*[starts-with(@id,'username')]") self.input_psw=(By.XPATH,"//*[@id='password']") self.login_button=(By.XPATH,"//button[contains(@id,'btnLogin')]") def login(self,name,psw): WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.input_name)).send_keys(name) WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.input_psw)).send_keys(psw) WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.login_button)).click() # 实例化调用登录商城类 if __name__ == '__main__': # 实例化webdirver driver = webdriver.Chrome() # 打开浏览器 driver.get("http://XXXX:38090/#/login") # 将driver传给类,实例化一个对象l l=login_shop(driver) # l 调用方法 l.login(name='朝天宫383',psw='123456') sleep(2) driver.quit()