def login(self, url='http://sddev.saimoyun.cn/#/login', userLoginPath='C:\Users\saimo\Desktop\Postman_Practice_file\登录.xlsx'): driver.get(url) wb = openpyxl.load_workbook(userLoginPath) # 选择工作表 ws = wb.active # 读取单元格数据, 赋值给变量 userName = ws['B1'].value passWord = ws['B2'].value # # 使用xpath定位需要操作的元素,并进行相应的操作 time.sleep(2) xpath_userName = ws['B5'].value element_userName = driver.find_element(By.XPATH, xpath_userName) # 定位输入账号位置 element_userName.click() # 进行单机操作 element_userName.send_keys(userName) # 输入用户名 # 如果需要输入文本,可以使用send_keys()方法。 # 定位输入账号位置, 进行单机操作 xpath_passWord = ws['B6'].value element_passWord = driver.find_element(By.XPATH, xpath_passWord) # 定位输入密码位置 element_passWord.send_keys(passWord) # 输入密码 # 拖动滑块右移300 xpath_slider = ws['B7'].value element_slider = driver.find_element(By.XPATH, xpath_slider) ActionChains(driver).click_and_hold(element_slider).move_by_offset(350, 0).release().perform() xpath_login = ws['B8'].value element_login = driver.find_element(By.XPATH, xpath_login) # 定位登录按钮, element_login.click() # 进行单机操作 print('用户登录成功') 这个如何进行封装?
时间: 2024-04-04 20:31:50 浏览: 92
可以将这段代码封装成一个类,例如:
```python
import time
import openpyxl
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
class LoginPage:
def __init__(self, driver):
self.driver = driver
def login(self, url='http://sddev.saimoyun.cn/#/login', userLoginPath='C:\Users\saimo\Desktop\Postman_Practice_file\登录.xlsx'):
self.driver.get(url)
wb = openpyxl.load_workbook(userLoginPath)
ws = wb.active
userName = ws['B1'].value
passWord = ws['B2'].value
time.sleep(2)
xpath_userName = ws['B5'].value
element_userName = self.driver.find_element(By.XPATH, xpath_userName)
element_userName.click()
element_userName.send_keys(userName)
xpath_passWord = ws['B6'].value
element_passWord = self.driver.find_element(By.XPATH, xpath_passWord)
element_passWord.send_keys(passWord)
xpath_slider = ws['B7'].value
element_slider = self.driver.find_element(By.XPATH, xpath_slider)
ActionChains(self.driver).click_and_hold(element_slider).move_by_offset(350, 0).release().perform()
xpath_login = ws['B8'].value
element_login = self.driver.find_element(By.XPATH, xpath_login)
element_login.click()
print('用户登录成功')
```
这样就可以通过创建 `LoginPage` 类的实例来调用 `login` 方法,例如:
```python
from selenium import webdriver
driver = webdriver.Chrome()
login_page = LoginPage(driver)
login_page.login()
```
阅读全文