selenium自动化公共方法的封装
时间: 2023-10-06 17:08:24 浏览: 119
Selenium自动化测试中,为了提高代码的可维护性和复用性,通常会对一些常用的操作进行封装,以便在不同的测试用例中重复使用。
以下是一些常见的Selenium自动化公共方法的封装:
1. 打开浏览器并访问URL
```python
from selenium import webdriver
def open_browser(url):
driver = webdriver.Chrome()
driver.get(url)
return driver
```
2. 查找元素
```python
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def find_element(driver, locator, timeout=10):
element = WebDriverWait(driver, timeout).until(
EC.presence_of_element_located(locator)
)
return element
```
3. 点击元素
```python
def click_element(driver, locator, timeout=10):
element = find_element(driver, locator, timeout)
element.click()
```
4. 输入文本
```python
def input_text(driver, locator, text, timeout=10):
element = find_element(driver, locator, timeout)
element.clear()
element.send_keys(text)
```
5. 获取元素文本
```python
def get_text(driver, locator, timeout=10):
element = find_element(driver, locator, timeout)
return element.text
```
6. 获取元素属性
```python
def get_attribute(driver, locator, attribute, timeout=10):
element = find_element(driver, locator, timeout)
return element.get_attribute(attribute)
```
7. 判断元素是否存在
```python
def is_element_exist(driver, locator, timeout=10):
try:
find_element(driver, locator, timeout)
return True
except:
return False
```
8. 切换窗口
```python
def switch_to_window(driver, window_index=1):
handles = driver.window_handles
driver.switch_to.window(handles[window_index])
```
9. 切换iframe
```python
def switch_to_iframe(driver, locator, timeout=10):
element = find_element(driver, locator, timeout)
driver.switch_to.frame(element)
```
10. 截屏
```python
def screenshot(driver, filename):
driver.save_screenshot(filename)
```
阅读全文