封装selenium相关的方法
时间: 2023-06-20 18:09:56 浏览: 53
好的,以下是一个简单的封装Selenium相关方法的示例:
```python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class SeleniumUtils:
def __init__(self, driver_path):
self.driver = webdriver.Chrome(executable_path=driver_path)
def get(self, url):
self.driver.get(url)
def find_element(self, locator, timeout=10):
element = WebDriverWait(self.driver, timeout).until(
EC.presence_of_element_located(locator)
)
return element
def click(self, locator):
element = self.find_element(locator)
element.click()
def send_keys(self, locator, keys):
element = self.find_element(locator)
element.send_keys(keys)
def clear(self, locator):
element = self.find_element(locator)
element.clear()
def close(self):
self.driver.close()
```
上述代码中,我们使用了Selenium的WebDriver API来实现浏览器的驱动和操作,同时也使用了一些等待和查找元素的API,例如`WebDriverWait`、`expected_conditions`、`By`等。我们封装了一些常用的方法,例如`get`、`click`、`send_keys`等,以方便我们进行页面操作。同时我们也有一个`close`方法,用于关闭浏览器。我们可以在实例化`SeleniumUtils`时传入ChromeDriver的路径,以便启动Chrome浏览器。
使用示例:
```python
selenium_utils = SeleniumUtils('/path/to/chromedriver')
selenium_utils.get('https://www.baidu.com')
search_input = selenium_utils.find_element((By.ID, 'kw'))
search_input.send_keys('Python')
search_input.send_keys(Keys.ENTER)
selenium_utils.close()
```
上述示例中,我们实例化了一个`SeleniumUtils`对象,然后使用`get`方法打开了百度首页,接着使用`find_element`方法查找搜索框元素,并使用`send_keys`方法输入了"Python"关键字并按下了回车键,最后使用`close`方法关闭了浏览器。