利用python使用 selenium 自动填写网页表单并提交

仅为自己方便使用,不完全通用,可自行分析页面源码。
参考网址:
python+selenium 自动填写表单并提交
Python+Selenium实现问卷星自动填写和选择
python selenium+Firefox 模拟浏览器操作

需求说明

在这里插入图片描述

目标就是自动填入上面的两个框,并模拟点击提交操作。

环境说明

  • pip install selenium
  • 安装驱动,chrome的点我,火狐的点我
  • 添加环境变量,例如我用狐火,就把火狐的启动程序的地址C:\Program Files\Mozilla Firefox\firefox.exe添加到path变量中。(这一步非必须,可以在代码中加上上面的地址)

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

firefox_options = Options()
firefox_options.add_argument('--headless')
firefox_options.add_argument('--disable-gpu')
driver = webdriver.Firefox(firefox_options=firefox_options)
## 没添加环境变量用下面这句
# driver = webdriver.Firefox(executable_path=r'C:\Program Files\Mozilla Firefox\firefox.exe')

# 请求页面
driver.get("http://euvt6102dqmg1y28.mikecrm.com/PB0LpfC")

# 姓名
driver.find_elements_by_class_name('fb_componentBody')[0].click()
driver.switch_to.active_element.send_keys("Test")

# 学号
driver.find_elements_by_class_name('fb_componentBody')[1].click()
driver.switch_to.active_element.send_keys("11")

# 提交
jSubmit = driver.find_element_by_class_name('submit')
jSubmit.click()
driver.close()