使用Python selenium类库模拟手人工操作网页
- 背景
- 准备工作
- 安装Python版本
- 安装selenium类库
- 下载selenium驱动
- 配置本地环境变量
- 自动化脚本输出
- 页面表单自动化填充相关代码
背景
- 待操作网页必须使用IE浏览器登录访问
- 用户本地只有edge浏览器,通过edge浏览器IE模式访问指定网页
验证结论:
selenium不支持通过edge浏览器IE模式控制网页。
目的:
通过本次实践,本文详细描述selenium使用过程,如环境配置方法以及基础网页表单填充,按钮点击等操作。
准备工作
安装Python版本
python官网下载python版本,推荐稳定发布版本,如python 3.13.2
安装selenium类库
打开本地cmd窗口,执行以下命令下载selenium类库
pip install selenium
查看selenium Python类库官方文档,各版本功能介绍等。
下载selenium驱动
chrome,edge,Firefox等高级浏览器驱动在selenium官网获取,IE浏览器驱动可以下载附件,包含32位和64位版本。
配置本地环境变量
为保证Python脚本正常读取webDriver驱动文件,须配置环境变量,对应值为驱动所在目录。
自动化脚本输出
python脚本运行自动初始化打开浏览器,相关代码如下。
注意:只能重新打开浏览器,不能基于已打开网页操作,各位酌情选择。
def init_driver(logger, browser_name, url):options = Options()# 脚本运行完不关闭网页options.add_experimental_option("detach", True)# 禁用扩展options.add_experimental_option('useAutomationExtension', False)# 添加agent头,绕过IE浏览器检查options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36')if browser_name == 'IE':# 继承个人主机配置,保留IE模式打开edge浏览器能力# options.add_argument(# "--user-data-dir=C:\\Users\\杨鹏\\AppData\\Local\\Microsoft\\Edge\\User Data") # 替换为你的实际用户数据目录路径options.add_argument("--profile-directory=Default") # 使用默认配置文件driver = webdriver.Ie(options=options)elif browser_name == 'Edge':options.use_chromium = True # Ensure we are using the Chromium-based Edgeoptions.add_experimental_option("excludeSwitches", ["enable-automation"]) # 避免 WebDriver 检测driver = webdriver.Edge(options=options)else:logger.error("Unsupported browser. Use 'IE' or 'Edge'.")raise ValueError("Unsupported browser. Use 'IE' or 'Edge'.")return driver
页面表单自动化填充相关代码
通过页面元素id等关键信息,定位页面元素,自动填充,包括文本框或者下拉列表选择。
def login(driver, url, username, password, user_phone):driver.get(url)username_input = driver.find_element(By.ID, 'tbUploadEndDate5')username_input.send_keys(username)password_input = driver.find_element(By.ID, 'tbUploadEndDate22')password_input.send_keys(password)# 图片验证码validate_code_input = driver.find_element(By.ID, 'validateCode')validate_code = input("请输入自动打开页面上的验证码计算结果: ")validate_code_input.send_keys(validate_code)# 找到手机号下拉列表元素user_phone_select_input = driver.find_element(By.ID, "userPhone") # 使用适当的定位器# 创建Select对象user_phone_select = Select(user_phone_select_input)# 根据文本选择选项user_phone_select.select_by_visible_text(user_phone)# 短信验证码发送verification_code_input = driver.find_element(By.ID, 'verificationCode')send_msg_button = driver.find_element(By.ID, 'sendBtn')# send_msg_button.click()verification_code = input("请输入您收到的短信验证码: ")# 短信验证码verification_code_input.send_keys(verification_code)login_img = driver.find_element(By.XPATH, "//td/img[@onclick='javascript:submitform();']")login_img.click()# 等待登录成功(可以根据实际情况调整等待条件)WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.ID, 'some_element_after_login')))