selenium 常用方法

selenium 库的常用方法:

方法 说明 示例代码
webdriver.Chrome() 初始化 Chrome 浏览器实例。 driver = webdriver.Chrome()
driver.get(url) 访问指定的 URL 地址。 driver.get("https://example.com")
driver.find_element(By, value) 查找第一个匹配的元素。 element = driver.find_element(By.ID, "id")
driver.find_elements(By, value) 查找所有匹配的元素。 elements = driver.find_elements(By.CLASS_NAME, "class")
element.click() 点击元素。 element.click()
element.send_keys(value) 向输入框中发送键盘输入。 element.send_keys("text")
element.text 获取元素的文本内容。 text = element.text
driver.back() 浏览器后退。 driver.back()
driver.forward() 浏览器前进。 driver.forward()
driver.refresh() 刷新当前页面。 driver.refresh()
driver.execute_script(script, *args) 执行 JavaScript 脚本。 driver.execute_script("alert('Hello!')")
driver.switch_to.frame(frame_reference) 切换到指定的 iframe。 driver.switch_to.frame("frame_id")
driver.switch_to.default_content() 切换回主文档。 driver.switch_to.default_content()
driver.quit() 关闭浏览器并退出驱动。 driver.quit()
driver.close() 关闭当前窗口。 driver.close()
复制代码
driver.find_element 返回的是 `WebElement` 对象,它具有以下常见方法:

### 交互操作方法
- `click()`:模拟鼠标点击元素。
- `send_keys(*value)`:向可输入元素(如文本框)输入文本。
- `clear()`:清除可输入元素中的文本内容。
- `submit()`:提交表单元素。

### 属性和信息获取方法
- `get_attribute(name)`:获取元素指定属性的值。
- `get_property(name)`:获取元素的指定属性。
- `text`:获取元素的可见文本内容。
- `tag_name`:获取元素的标签名。

### 状态判断方法
- `is_displayed()`:判断元素是否在页面上可见。
- `is_enabled()`:判断元素是否处于可用状态。
- `is_selected()`:判断元素(如复选框、单选框)是否被选中。

### 位置和尺寸信息方法
- `size`:获取元素的尺寸,返回包含 `width` 和 `height` 的字典。
- `location`:获取元素在页面上的位置,返回包含 `x` 和 `y` 坐标的字典。
- `rect`:获取元素的位置和大小信息,返回包含 `x`、`y`、`width` 和 `height` 的字典。

### 元素查找方法
- `find_element(by=By.ID, value=None)`:在当前元素的子元素中查找单个元素。
- `find_elements(by=By.ID, value=None)`:在当前元素的子元素中查找多个元素,返回元素列表。

### 其他方法
- `screenshot(filename)`:对元素进行截图并保存为指定文件。
- `screenshot_as_png`:以 PNG 格式返回元素的截图数据。
- `screenshot_as_base64`:以 Base64 编码字符串形式返回元素的截图数据。
- `value_of_css_property(property_name)`:获取元素指定 CSS 属性的值。
相关推荐
橘颂TA8 小时前
【测试】自动化测试函数介绍——web 测试
python·功能测试·selenium·测试工具·dubbo
流㶡10 小时前
Python爬虫:POST与Selenium
爬虫·python·selenium
0思必得01 天前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
uyeonashi2 天前
Boost搜索引擎测试报告
功能测试·selenium·搜索引擎
@zulnger2 天前
selenium 自动化测试工具实战项目(订单)
selenium·测试工具·自动化
程序员三藏3 天前
selenium测试框架快速搭建
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
不会代码的小测试3 天前
UI自动化-日期插件的选择-可输入不可输入情况
javascript·vue.js·python·selenium·自动化
月明长歌4 天前
个人测试项目:一个可跑、可扩、可复用的 Selenium UI 自动化博客系统全链路测试拆解
selenium·ui·自动化
0思必得04 天前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
不会代码的小测试5 天前
UI自动化-针对验证码登录的系统,通过首次手动登录存储cookie的方式后续访问免登录方法
开发语言·python·selenium