Python-Selenium 库详解_selenium库
一、Selenium 库简介
Selenium 是 Python 生态中 最主流的 Web 自动化测试工具,支持通过代码模拟用户操作浏览器行为。其核心特性包括:
- 多浏览器支持:兼容 Chrome、Firefox、Edge、Safari 等主流浏览器。
- 跨平台性:可在 Windows、macOS、Linux 上运行,适配不同开发环境。
- 功能覆盖全面:支持点击、输入、拖拽、文件上传、弹窗处理等操作,满足自动化测试、爬虫、数据采集等场景需求。
- 动态内容处理:通过等待机制(显式/隐式)解决 AJAX 加载、动态渲染等问题。
二、安装与配置
- 安装库:
bash
pip install selenium
- 下载浏览器驱动(以 Chrome 为例):
- 从 ChromeDriver 官网下载对应浏览器版本的驱动。
- 将驱动文件路径添加到系统环境变量,或在代码中指定路径。
三、核心功能与常用函数
1. 浏览器操作
webdriver.Chrome()
**python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(url)
**python
driver.get(\"https://www.baidu.com\")
driver.title
**python
print(\"标题:\", driver.title)
driver.quit()
**python
driver.quit()
2. 元素定位
Selenium 提供 8 种元素定位方式,常用方法如下:
driver.find_element(By.ID, \"username\")
driver.find_element(By.XPATH, \"//input[@class=\'search\']\")
driver.find_element(By.CSS_SELECTOR, \"#submit > span\")
driver.find_element(By.CLASS_NAME, \"btn-primary\")
driver.find_element(By.LINK_TEXT, \"立即登录\")
driver.find_element(By.PARTIAL_LINK_TEXT, \"登录\")
driver.find_element(By.TAG_NAME, \"input\")
driver.find_element(By.NAME, \"password\")
3. 元素操作
send_keys(text)
**python
search_box = driver.find_element(By.ID, \"kw\")
search_box.send_keys(\"Python\")
click()
**python
login_button.click()
clear()
**python
search_box.clear()
submit()
**python
search_box.submit()
text
属性**python
print(\"按钮文本:\", button.text)
4. 等待机制
处理动态加载内容的关键方法:
python
driver.implicitly_wait(10) # 所有元素查找最多等 10 秒
python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"dynamic_element\")))
5. 高级交互
ActionChains
类模拟悬停、拖拽等行为python
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
actions.drag_and_drop(source, target).perform()
Keys
类模拟快捷键(如回车、Ctrl+C)python
from selenium.webdriver.common.keys import Keys
search_box.send_keys(Keys.CONTROL + \'a\')
send_keys()
直接传入文件路径python
upload_element = driver.find_element(By.ID, \"file_input\")
upload_element.send_keys(\"/path/to/file.png\")
python
alert = driver.switch_to.alert
alert.accept() # 确认
python
handles = driver.window_handles
driver.switch_to.window(handles[1])
python
driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")
python
driver.save_screenshot(\"page.png\")
element.screenshot(\"element.png\")
四、应用场景
- 自动化测试
- 验证 Web 应用功能(如登录、表单提交)。
- 跨浏览器兼容性测试。
- 数据采集
- 抓取动态渲染的网页数据(如电商价格、社交媒体内容)。
- 业务流程自动化
- 自动填写报表、批量上传文件。
- 定时签到、抢购脚本。
五、注意事项
- 驱动版本匹配
- 浏览器与驱动版本需严格对应,否则会报错。
- 反爬机制规避
- 添加随机等待、使用代理 IP 避免被封禁。
- 性能优化
- 使用
find_elements
(返回列表)替代多次find_element
。 - 避免不必要的全局隐式等待。
- 使用
- 异常处理
- 捕获
NoSuchElementException
、TimeoutException
等常见异常。
- 捕获