以下代码是由我编写的,但是我发现该方法有时不合适。我不知道如何制作出良好的super
方法来涵盖四个基本的Selenium Web驱动器方法。
def keymouse(url, operation , elementxpath):
driver = webdriver.Chrome()
driver.get(url)
time.sleep(1)
driver.maximize_window()
time.sleep(1)
operation_by = operation.split('.')[1]
if operation_by == "context_click()":
result = ActionChains(driver).context_click(driver.find_element_by_xpath(elementxpath)).perform()
if operation_by == "double_click()":
result = ActionChains(driver).double_click(driver.find_element_by_xpath(elementxpath)).perform()
if operation_by == "drag_and_drop()":
result = ActionChains(driver).drag_and_drop(driver.find_element_by_xpath(elementxpath), driver.find_element_by_xpath(elementxpath)).perform()
if operation_by == "click_and_hold()":
result = ActionChains(driver).click_and_hold(driver.find_element_by_xpath(elementxpath)).perform()
else:
time.sleep(3)
这是使用上述方法的实例:
from method.key_mouse import *
#driver = webdriver.Chrome()
keymouse("https://www.baidu.com", "operation.context_click()", "//*[@id='kw']")
一种好方法是使用枚举模块。
from enum import Enum
# Create your desired operations
class KeyMouseOperation(Enum):
CONTEXT_CLICK = 1
DOUBLE_CLICK = 2
DRAG_AND_DROP = 3
CLICK_AND_HOLD = 4
from method.key_mouse import *
#driver = webdriver.Chrome()
keymouse("https://www.baidu.com", KeyMouseOperation.CONTEXT_CLICK, "//*[@id='kw']")
def keymouse(url, operation , elementxpath):
driver = webdriver.Chrome()
driver.get(url)
time.sleep(1)
driver.maximize_window()
time.sleep(1)
if operation_by == KeyMouseOperation.CONTEXT_CLICK:
result = ActionChains(driver).context_click(driver.find_element_by_xpath(elementxpath)).perform()
if operation_by == KeyMouseOperation.DOUBLE_CLICK:
result = ActionChains(driver).double_click(driver.find_element_by_xpath(elementxpath)).perform()
if operation_by == KeyMouseOperation.DRAG_AND_DROP:
result = ActionChains(driver).drag_and_drop(driver.find_element_by_xpath(elementxpath), driver.find_element_by_xpath(elementxpath)).perform()
if operation_by == KeyMouseOperation.CLICK_AND_HOLD:
result = ActionChains(driver).click_and_hold(driver.find_element_by_xpath(elementxpath)).perform()
else:
time.sleep(3)