python中selenium怎么使用

安装与配置

确保已安装Python环境,通过pip安装Selenium库:

复制代码
pip install selenium

下载对应浏览器的WebDriver(如ChromeDriver),将其路径添加到系统环境变量或直接在代码中指定路径。

基本使用示例

导入Selenium库并启动浏览器:

python 复制代码
from selenium import webdriver
driver = webdriver.Chrome()  # 使用Chrome浏览器
driver.get("https://www.example.com")  # 打开网页

元素定位

常用定位方法:

python 复制代码
# 通过ID定位
element = driver.find_element_by_id("id_value")

# 通过类名定位
element = driver.find_element_by_class_name("class_name")

# 通过XPath定位
element = driver.find_element_by_xpath("//input[@name='username']")

交互操作

输入文本与点击按钮:

python 复制代码
element.send_keys("text")  # 输入文本
element.click()  # 点击元素

等待机制

显式等待(推荐):

python 复制代码
from selenium.webdriver.common.by import By
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, "id_value"))
)

关闭浏览器

结束操作后关闭浏览器:

python 复制代码
driver.quit()  # 关闭所有窗口并退出驱动

常见问题处理

处理弹窗:

python 复制代码
alert = driver.switch_to.alert
alert.accept()  # 确认弹窗

切换iframe:

python 复制代码
driver.switch_to.frame("frame_name_or_id")

高级技巧

执行JavaScript代码:

python 复制代码
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

截图保存:

python 复制代码
driver.save_screenshot("screenshot.png")
相关推荐
AI探索者11 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者11 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh12 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅12 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽14 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时17 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿19 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python