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")
相关推荐
岁月宁静10 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者10 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy199012 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk55513 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~19 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享19 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者20 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.21 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人1 天前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__1 天前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python