商丘网站建设制作,怎么修改wordpress布局,常熟网站开发,网络营销毕业设计使用Python selenium类库模拟手人工操作网页 背景准备工作安装Python版本安装selenium类库下载selenium驱动配置本地环境变量 自动化脚本输出页面表单自动化填充相关代码 背景
待操作网页必须使用IE浏览器登录访问用户本地只有edge浏览器#xff0c;通过edge浏览器IE模式访问… 使用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驱动
chromeedgeFirefox等高级浏览器驱动在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-agentMozilla/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-dirC:\\Users\\杨鹏\\AppData\\Local\\Microsoft\\Edge\\User Data) # 替换为你的实际用户数据目录路径options.add_argument(--profile-directoryDefault) # 使用默认配置文件driver webdriver.Ie(optionsoptions)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(optionsoptions)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[onclickjavascript:submitform();])login_img.click()# 等待登录成功可以根据实际情况调整等待条件WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.ID, some_element_after_login)))