[Selenium][Notes]Day3:访问本地html&1️⃣操作form表单

176 阅读1分钟

image.png

访问本地html
# 重点:get(file:// + html路径)中的file://不能少
self.driver.get("file:////Users/admin/PycharmProjects/Test/Testcase/forms.html")

完整Code:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="javascript:alert('Hello')">
    Username: <input type="text" name="username" id="username"><br>
    Password: <input type="password" name="pwd" id="pwd"><br>
    <input type="submit" value="submit" id="submit">
</form>
</body>
</html>
Python
from selenium import webdriver
from time import sleep
import os

class TestCase(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        # path = os.path.abspath(__file__)  # 当前文件路径
        path = os.path.dirname(os.path.abspath(__file__))  # 当前文件所在目录路径
        # file协议拼接路径
        file_path = 'file:///' + path + '/forms.html'
        print(file_path)
        # 访问本地html
        self.driver.get(file_path)

    def test_login(self):
        username = self.driver.find_element_by_id('username')
        username.send_keys('Admin')   # username里输入内容
        pwd = self.driver.find_element_by_id('pwd')
        pwd.send_keys('Test!123')   # password里输入内容
        # 获取输入框的值
        print(username.get_attribute('value'))   
        print(pwd.get_attribute('value'))
        sleep(2)

        self.driver.find_element_by_id('submit').click()
        # 确认并关掉alert
        self.driver.switch_to.alert.accept()  
        sleep(1)
        # 清空内容
        username.clear()  
        pwd.clear()
        sleep(2)
        self.driver.quit()

if __name__ == '__main__':
    case = TestCase()
    case.test_login()