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")
相关推荐
朝朝辞暮i42 分钟前
从0开始学python(day2)
python
程序员黄同学1 小时前
Python中的列表推导式、字典推导式和集合推导式的性能和应用场景?
开发语言·python
AI小云1 小时前
【Python高级编程】类和实例化
开发语言·人工智能·python
道之极万物灭1 小时前
Python uv虚拟环境管理工具详解
开发语言·python·uv
高洁011 小时前
【无标题】大模型-模型压缩:量化、剪枝、蒸馏、二值化 (2
人工智能·python·深度学习·神经网络·知识图谱
一晌小贪欢1 小时前
Python爬虫第10课:分布式爬虫架构与Scrapy-Redis
分布式·爬虫·python·网络爬虫·python爬虫·python3
代码AI弗森2 小时前
Python × NumPy」 vs 「JavaScript × TensorFlow.js」生态全景图
javascript·python·numpy
paid槮2 小时前
Shell编程基本介绍
python
渣渣盟2 小时前
探索Word2Vec:从文本向量化到中文语料处理
前端·javascript·python·文本向量化
天天进步20153 小时前
Python全栈项目--基于计算机视觉的车牌识别系统
开发语言·python·计算机视觉