Selenium自动化测试:使用click_with_xpath函数点击按钮

在Selenium自动化测试中,经常需要点击按钮来执行操作。为了提高代码的可读性和可维护性,我们可以封装一个函数来专门处理按钮点击操作,例如click_with_xpath函数。

原代码示例:

if is_element_exist(self.driver, element.element_detail_edit_btn):
    self.driver.find_element(By.XPATH, element.element_detail_edit_btn).click()
elif is_element_exist(self.driver, OWT_EDIT_ELEMENT):
    self.driver.find_element(By.XPATH, OWT_EDIT_ELEMENT).click()


def is_element_exist(driver, xpath):
    try:
        driver.find_element(By.XPATH, xpath)
        return 1
    except NoSuchElementException:
        return 0

def click_with_xpath(self, by, xpath, front_sleep=3):
    '点击按钮'
    time.sleep(front_sleep)
    # 点击 按钮
    element = self.safe_get_elements(by, xpath)
    if element.is_enabled():
        return element.click()
    else:
        raise SpiderException(xpath=xpath)

使用click_with_xpath函数优化代码:

如果想在if-else语句中使用click_with_xpath函数,可以按照以下步骤进行:

  1. click_with_xpath函数的定义部分移动到is_element_exist函数的上方,以确保它在is_element_exist函数调用之前已经定义。
  2. click_with_xpath函数中添加一个额外的参数来指定等待按钮可点击的时间。
  3. 在if-else语句中使用click_with_xpath函数来点击按钮。

优化后的代码示例:

def is_element_exist(driver, xpath):
    try:
        driver.find_element(By.XPATH, xpath)
        return 1
    except NoSuchElementException:
        return 0

def click_with_xpath(driver, xpath, front_sleep=3):
    '点击按钮'
    time.sleep(front_sleep)
    # 点击按钮
    element = driver.find_element(By.XPATH, xpath)
    if element.is_enabled():
        return element.click()
    else:
        raise SpiderException(xpath=xpath)

if is_element_exist(self.driver, element.element_detail_edit_btn):
    click_with_xpath(self.driver, element.element_detail_edit_btn)
elif is_element_exist(self.driver, OWT_EDIT_ELEMENT):
    click_with_xpath(self.driver, OWT_EDIT_ELEMENT)

注意:在这个修改后的代码中,click_with_xpath函数不再是一个实例方法,它变成了一个普通函数,因此调用时不需要通过self来访问。

总结:

使用click_with_xpath函数可以提高代码的可读性和可维护性,并方便代码的复用。在实际应用中,还可以根据需要添加其他参数,例如超时时间、等待元素出现的条件等,以满足不同的需求。

Selenium自动化测试:使用click_with_xpath函数点击按钮

原文地址: https://www.cveoy.top/t/topic/qhV0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录