首先创建一个html,方便演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<! 说明 alert() 方法将在对话框中把指定的 message 显示给用户!>
<form action="javascript:alert('hello')">
Username: <input type="text" name="username" id="username"><br> <! br 换行 !>
Password: <input type="text" name="password" id="password"><br>
<input type="submit" value="submit" id="submit"> <! value 指input的值 !>
</form>
</body>
</html>
接着在.py里调用这个html
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
from time import sleep
# 配合 form.html文件操作
class Testcase(object):
def __init__(self):
self.driver = webdriver.Chrome()
# os.path.abspath(__file__): 获得该.py文件路径
# os.path.dir-name():获得路径名称 这里是获得.py文件所在路径
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///' + path + '/forms.html' # 获取登录forms.html的url
self.driver.get(file_path)
def get_login(self):
username = self.driver.find_element(By.ID, "username")
username.send_keys("admin")
password = self.driver.find_element(By.ID, "password")
password.send_keys(123456)
print(username.get_attribute('value'))
print(password.get_attribute('value'))
sleep(2)
self.driver.find_element(By.ID, "submit").click()
self.driver.switch_to.alert.accept() # 清空alert(效果看起来是点掉了那个‘确定’),才能执行clear
username.clear()
password.clear()
sleep(1000)
if __name__ == '__main__':
case = Testcase()
case.get_login()
个人理解在form表单定位元素可以更精准定位到需要的元素