Python Selenium 自动化测试:使用 click_with_xpath 函数封装元素点击操作
{/n/'title/': /'Python Selenium 自动化测试:使用 click_with_xpath 函数封装元素点击操作/',/n/'description/': /'本文介绍了如何使用 Python Selenium 中的 click_with_xpath 函数封装元素点击操作,并提供了一个完整的代码示例。该函数可以根据元素的 XPath 判断元素是否存在,并进行点击操作,简化代码并提高代码可读性。/',/n/'keywords/': /'Python, Selenium, 自动化测试, 元素点击, click_with_xpath, XPath, 代码封装, 代码示例/',/n/'content/': /'if is_element_exist(self.driver, element.element_detail_edit_btn)://n self.driver.find_element(By.XPATH, element.element_detail_edit_btn).click()//n elif is_element_exist(self.driver, OWT_EDIT_ELEMENT)://n self.driver.find_element(By.XPATH, OWT_EDIT_ELEMENT).click()//n//n//ndef is_element_exist(driver, xpath)://n try://n driver.find_element(By.XPATH, xpath)//n return 1//n except NoSuchElementException://n return 0//n//ndef click_with_xpath(self, by, xpath, front_sleep=3)://n /'/'点击按钮/'/'/n time.sleep(front_sleep)//n # 点击 按钮//n element = self.safe_get_elements(by, xpath)//n if element.is_enabled()://n return element.click()//n else://n raise SpiderException(xpath=xpath)//n//n如果 if is_element_exist(self.driver, element.element_detail_edit_btn)://n self.driver.find_element(By.XPATH, element.element_detail_edit_btn).click()//n elif is_element_exist(self.driver, OWT_EDIT_ELEMENT)://n self.driver.find_element(By.XPATH, OWT_EDIT_ELEMENT).click()这一段想使用click_with_xpath,该怎么做,如果不能实现,参照click_with_xpath重新写一个封装内容:您可以修改click_with_xpath函数,使其接受一个元素的xpath作为参数,然后在函数内部使用is_element_exist函数来判断该元素是否存在,并进行点击操作。//n//n修改后的click_with_xpath函数如下所示://n//ndef click_with_xpath(self, xpath, front_sleep=3)://n /'/'点击按钮/'/'/n time.sleep(front_sleep)//n # 判断元素是否存在//n if is_element_exist(self.driver, xpath)://n element = self.driver.find_element(By.XPATH, xpath)//n if element.is_enabled()://n return element.click()//n else://n raise SpiderException(xpath=xpath)//n else://n raise SpiderException(xpath=xpath)//n//n然后您可以将原来的代码修改为://n//nif is_element_exist(self.driver, element.element_detail_edit_btn)://n click_with_xpath(self.driver, element.element_detail_edit_btn)//nelif is_element_exist(self.driver, OWT_EDIT_ELEMENT)://n click_with_xpath(self.driver, OWT_EDIT_ELEMENT)//n//n这样就可以实现使用click_with_xpath函数来进行元素点击操作了。/'}/
原文地址: https://www.cveoy.top/t/topic/qhV2 著作权归作者所有。请勿转载和采集!