Skip to content

Selenium 的详细使用指南,涵盖安装、浏览器自动化、元素操作及常见场景示例:


1. 安装

bash
# 安装 Python 包
pip install selenium

# 下载浏览器驱动(如 ChromeDriver)
# 地址:https://sites.google.com/chromium.org/driver/
# 确保驱动版本与浏览器版本匹配

2. 基本用法

启动浏览器(以 Chrome 为例)

python
from selenium import webdriver
from selenium.webdriver.common.by import By

# 指定驱动路径(或添加到系统 PATH)
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
driver.get("https://example.com")

# 获取页面标题
print(driver.title)

# 关闭浏览器
driver.quit()

3. 元素定位

常用定位方式

python
# 通过 ID
element = driver.find_element(By.ID, "username")

# 通过类名
element = driver.find_element(By.CLASS_NAME, "input-field")

# 通过 CSS 选择器
element = driver.find_element(By.CSS_SELECTOR, "button.submit")

# 通过 XPath
element = driver.find_element(By.XPATH, "//div[@id='content']/p")

# 通过链接文本
element = driver.find_element(By.LINK_TEXT, "点击这里")

批量定位元素

python
elements = driver.find_elements(By.TAG_NAME, "a")
for link in elements:
    print(link.text)

4. 元素操作

输入文本与点击

python
# 输入文本
driver.find_element(By.ID, "username").send_keys("admin")

# 清空输入框
driver.find_element(By.ID, "username").clear()

# 点击按钮
driver.find_element(By.CSS_SELECTOR, "button.submit").click()

处理下拉框

python
from selenium.webdriver.support.select import Select

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_value("CN")  # 按值选择
dropdown.select_by_visible_text("中国")  # 按文本选择

5. 等待机制

显式等待(推荐)

python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待元素出现(最多 10 秒)
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "dynamic-content"))
)

# 等待元素可点击
button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, "button.load-more"))
)
button.click()

隐式等待(全局)

python
driver.implicitly_wait(10)  # 每次查找元素最多等待 10 秒

6. 处理常见场景

切换窗口/标签页

python
# 获取当前窗口句柄
main_window = driver.current_window_handle

# 点击打开新标签页
driver.find_element(By.LINK_TEXT, "新页面").click()

# 切换到新窗口
for handle in driver.window_handles:
    if handle != main_window:
        driver.switch_to.window(handle)
        break

# 关闭新窗口并切回原窗口
driver.close()
driver.switch_to.window(main_window)

处理弹窗/Alert

python
alert = driver.switch_to.alert
print(alert.text)
alert.accept()  # 确认
# alert.dismiss()  # 取消

上传文件

python
file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
file_input.send_keys("/path/to/file.txt")

7. 高级功能

无头模式(Headless)

python
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")  # 启用无头模式
driver = webdriver.Chrome(options=options)

执行 JavaScript

python
# 滚动到页面底部
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

# 修改元素属性
driver.execute_script("arguments[0].style.border='3px solid red';", element)

截图

python
driver.save_screenshot("screenshot.png")
element.screenshot("element_screenshot.png")

8. 集成其他工具

结合 BeautifulSoup 解析

python
from bs4 import BeautifulSoup

html = driver.page_source
soup = BeautifulSoup(html, "html.parser")
title = soup.find("h1").text

在 Scrapy 中使用 Selenium

python
# 中间件示例(需在 Scrapy 中配置)
from scrapy.http import HtmlResponse


class SeleniumMiddleware:
    def process_request(self, request, spider):
        driver = webdriver.Chrome()
        driver.get(request.url)
        html = driver.page_source
        driver.quit()
        return HtmlResponse(url=request.url, body=html, encoding='utf-8')

9. 常见问题解决

  1. 元素找不到(NoSuchElementException)

    • 检查定位器是否正确(如动态生成的 ID)。
    • 增加显式等待或隐式等待时间。
    • 确认元素是否在 iframe 中(需切换上下文)。
  2. 浏览器版本与驱动不匹配

    • 使用 driver.service.path 检查驱动路径。
    • 更新浏览器和驱动到相同版本。
  3. 跨域限制

    • 无法通过 Selenium 直接绕过,需通过代理或修改浏览器配置。

10. 性能优化建议

  • 使用无头模式减少资源占用。
  • 复用浏览器会话(避免频繁启动/关闭)。
  • 通过 options.add_argument("--disable-gpu") 禁用 GPU 加速。

通过 Selenium,可实现浏览器自动化测试、动态网页爬取(如 JavaScript 渲染内容)和复杂交互模拟,适用于需完整浏览器环境的场景。

✨ 网站运行时间: 3年11月15天 ❤️ 道阻且长,行则将至 - 微信号: heikedreamer