Python自动化浏览器操作与定时任务实战指南
在日常工作中,我们经常需要重复执行一些网页操作,比如登录系统、填写表单、数据采集等。手动操作不仅耗时,还容易出错。本文将介绍如何使用Python实现浏览器自动化操作,并将其设置为定时任务,让计算机自动完成这些重复性工作。
技术栈选择
-
Selenium: 浏览器自动化框架,支持多种浏览器
-
Chrome WebDriver: Chrome浏览器驱动
-
Schedule/APScheduler: Python定时任务库
-
Python 3.7+: 编程语言
环境准备
1. 安装必要的库
pip install selenium
pip install schedule
pip install webdriver-manager
2. 准备浏览器驱动
使用webdriver-manager可以自动管理驱动,无需手动下载:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
核心功能实现
1. 浏览器自动登录
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import timeclass BrowserAutomation:def __init__(self):"""初始化浏览器"""options = webdriver.ChromeOptions()# 可选: 无头模式(后台运行)# options.add_argument('--headless')options.add_argument('--disable-blink-features=AutomationControlled')options.add_argument('--start-maximized')self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)self.wait = WebDriverWait(self.driver, 10)def login(self, url, username, password):"""自动登录网站:param url: 登录页面URL:param username: 用户名:param password: 密码"""try:# 打开登录页面self.driver.get(url)print(f"正在访问: {url}")# 等待页面加载完成,找到用户名输入框username_input = self.wait.until(EC.presence_of_element_located((By.ID, "username")))username_input.clear()username_input.send_keys(username)print("已输入用户名")# 找到密码输入框password_input = self.driver.find_element(By.ID, "password")password_input.clear()password_input.send_keys(password)print("已输入密码")# 点击登录按钮