Selenium测试本地web登录
首先在py项目上配置selenium
配置好了之后上代码(末尾有完整代码)
首先导包
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
登录界面的网址
driver.get('http://localhost:8889/xuejiguanli_war_exploded/index.jsp')
登录界面的原代码中可以看到是四个定位
<p class="ziti">账号:<input type="text" name="zhanghao" class="select" placeholder="学号"></p>
<p> </p>
<p class="ziti">密码:<input type="password" name="password" class="select"></p>
<p> </p>
<p class="ziti">身份:<select id="shenfen" name="shenfen" class="select">
<option value="">请选择您的身份</option>
<option value="在校生">在校生</option>
<option value="管理员">管理员</option>
</select> </p>
<p> </p>
<button type="submit" id="submit">登录</button>
两个文本输入定位,一个下拉框定位,一个按钮定位
因此我们的测试脚本也是四个
文本定位
driver.find_element(By.NAME,'zhanghao').send_keys('juzipi')
time.sleep(1)
driver.find_element(By.NAME, 'password').send_keys('51129')
time.sleep(1)
下拉框(这里选用的是定位到文本,还有其他定位方法可以自行搜索)
nr = driver.find_element(By.ID, "shenfen")
# 实例化
select = Select(nr)
select.select_by_visible_text("管理员")
time.sleep(1)
提交按钮
button = driver.find_element(By. ID, 'submit')
button.click()
运行成功后就会打开网页,自动补充账号密码和身份,登陆成功
完整代码
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
options = webdriver.ChromeOptions()
options.add_experimental_option('detach', True)
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(10)
time.sleep(1)
driver.get('http://localhost:8889/xuejiguanli_war_exploded/index.jsp')
time.sleep(1)
driver.find_element(By.NAME,'zhanghao').send_keys('juzipi')
time.sleep(1)
driver.find_element(By.NAME, 'password').send_keys('51129')
time.sleep(1)
nr = driver.find_element(By.ID, "shenfen")
# 实例化
select = Select(nr)
select.select_by_visible_text("管理员")
time.sleep(1)
button = driver.find_element(By. ID, 'submit')
button.click()
style = driver.find_element(By.TAG_NAME,'style')
assert style !=[]