爬虫基础之自动化工具 Selenium 的使用
字数 765 2025-08-11 08:36:31
Selenium 自动化工具使用详解
概述
Selenium 是一个流行的自动化测试框架,可用于测试 Web 应用程序的用户界面。它支持多种编程语言(如 Java、Python、Ruby 等),并提供了一系列 API 可以直接操作浏览器进行测试。
适用场景
- 采集采用 Ajax 等技术动态加载数据的网站
- 避免复杂的抓包和逆向分析过程
- 直接获取数据加载完成后的网页源码
安装与配置
1. 下载浏览器驱动
以谷歌浏览器为例:
- 访问驱动下载页面
- 找到与浏览器版本最接近的驱动文件(如浏览器版本为 112.0.5615.86,可选择 112.0.5615.49)
- 下载对应系统版本的压缩包
- 将压缩包中的
chromedriver.exe程序放到 Python 目录下
2. 安装 Selenium 库
pip install selenium
基本使用
初始化浏览器对象
from selenium import webdriver
# 初始化浏览器对象
driver = webdriver.Chrome()
# 打开目标网址
driver.get('https://www.baidu.com/')
# 打印当前页面源代码
print(driver.page_source)
# 关闭浏览器
driver.quit()
元素定位方法
Selenium 提供了多种元素定位方法:
from selenium.webdriver.common.by import By
# 根据 XPath 定位
driver.find_elements(By.XPATH, '//div[@class="slider_list"]/div/a[@class="slider_item seckill-item slider_active"]')
# 根据 CSS 选择器定位
driver.find_elements(By.CSS_SELECTOR, 'a[class="slider_item seckill-item slider_active"]')
# 根据类名定位
driver.find_elements(By.CLASS_NAME, 'seckill-item')
# 根据 ID 定位
driver.find_elements(By.ID, 'ID')
# 根据链接文本定位
driver.find_elements(By.LINK_TEXT, 'LINK_TEXT')
# 根据部分链接文本定位
driver.find_elements(By.PARTIAL_LINK_TEXT, 'PARTIAL_LINK_TEXT')
# 根据标签名定位
driver.find_elements(By.TAG_NAME, 'TAG_NAME')
元素交互
Selenium 可以实现对页面元素的点击、输入等操作:
# 获取搜索框
search = driver.find_element(By.XPATH, '//div[@role="serachbox"]/input')
# 获取查询按钮
button = driver.find_element(By.XPATH, '//div[@role="serachbox"]/button')
# 在搜索框中输入 Python
search.send_keys('Python')
# 点击查询按钮
button.click()
等待机制
1. 不等待页面完全加载
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "none" # 不等待页面加载
driver = webdriver.Chrome(desired_capabilities=caps)
2. 强制等待(不推荐)
import time
driver.get('https://www.jd.com/')
time.sleep(6) # 强制休眠6秒
3. 隐式等待(不推荐)
driver.implicitly_wait(10) # 隐式等待10秒
driver.get('https://www.jd.com/')
4. 显式等待(推荐)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import selenium.common.exceptions
try:
WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located(
(By.CSS_SELECTOR, 'a[class="slider_item seckill-item slider_active"]')
)
)
except selenium.common.exceptions.TimeoutException:
print('元素加载超时')
动作 API
鼠标操作
from selenium.webdriver import ActionChains
# 单击元素并按住
clickable = driver.find_element(By.ID, "clickable")
ActionChains(driver).click_and_hold(clickable).perform()
# 双击
ActionChains(driver).double_click(clickable).perform()
# 按偏移量移动鼠标
mouse_tracker = driver.find_element(By.ID, "mouse-tracker")
ActionChains(driver).move_to_element_with_offset(mouse_tracker, 8, 0).perform()
# 按当前指针位置进行偏移
ActionChains(driver).move_by_offset(13, 15).perform()
# 按偏移拖放
draggable = driver.find_element(By.ID, "draggable")
start = draggable.location
finish = driver.find_element(By.ID, "droppable").location
ActionChains(driver).drag_and_drop_by_offset(
draggable,
finish['x'] - start['x'],
finish['y'] - start['y']
).perform()
滚轮操作
# 滚动到指定元素
iframe = driver.find_element(By.TAG_NAME, "iframe")
ActionChains(driver).scroll_to_element(iframe).perform()
# 按给定值滚动
footer = driver.find_element(By.TAG_NAME, "footer")
delta_y = footer.rect['y']
ActionChains(driver).scroll_by_amount(0, delta_y).perform()
反检测技术
Selenium 容易被网站检测到,可以通过以下方法隐藏特征:
from selenium import webdriver
from selenium.webdriver import ChromeOptions
options = ChromeOptions()
# 以最高权限运行
options.add_argument('--no-sandbox')
# navigator.webdriver 设置为 false
options.add_argument("--disable-blink-features=AutomationControlled")
# 隐藏"Chrome正在受到自动软件的控制"提示
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options)
# 加载反检测脚本
with open('./stealth.min.js', 'r') as f:
js = f.read()
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js})
获取 stealth.min.js
如果已安装 Node.js,执行以下命令生成 stealth.min.js 文件:
npx extract-stealth-evasions
无头模式
无头模式下浏览器不会弹出窗口,适合服务器环境使用:
options = ChromeOptions()
options.add_argument('--headless') # 启用无头模式
driver = webdriver.Chrome(options=options)
优缺点分析
优势
- 使用简单,不需要对网站进行调试
- 不需要关注数据来源
- 大大减少爬虫程序开发时间
劣势
- 采集效率低
- 资源占用大
- 不稳定
- 容易被检测
- 依赖 WebDriver,需要随浏览器更新而更新
适用场景
Selenium 适用于逆向难度较大且对采集效率要求不高的场景。