Python Selenium:定位元组传入click方法格式报错求解
Python Selenium 定位器传参问题修复方案
问题场景
开发Selenium自动化测试框架时,定义页面元素定位器、封装通用点击方法后,调用方法时出现参数不匹配、星号表达式语法报错。
定位器类定义
from selenium.webdriver.common.by import By class SearchCustomerLocators: txtEmail_id = (By.ID, "SearchEmail") txtFirstName_id = (By.ID,"SearchFirstName") txtLastName_id = (By.ID,"SearchLastName") btnSearch_id = (By.ID,"search-customers")
错误调用写法
self.click(*SearchCustomerLocators.txtEmail_xpath)
封装的click方法逻辑
from selenium.webdriver.support import expected_conditions def click(self, webelement): #self._driver.execute_script("arguments[0].scrollIntoView();", webelement) el = self._wait.until(expected_conditions.element_to_be_clickable(webelement)) self._highlight_element(el, "green") el.click()
报错原因
- 封装的
click方法仅接收1个入参:格式为(定位方式, 定位表达式)的完整元组,例如('xpath', "//button[@type='submit']"),该参数会直接传给element_to_be_clickable条件做元素等待 - 调用时使用
*运算符对定位元组解包,会把原本的1个元组拆成2个独立的位置参数传入,和方法入参要求不符 - 直接写
x = *SearchCustomerLocators.txtEmail_xpath不符合Python赋值语法,会触发Can't use starred expression here语法错误
修复方法
调用方法时去掉*解包运算符,直接传入定位器类中定义的元组本身即可:
# 正确调用写法 self.click(SearchCustomerLocators.txtEmail_id)
补充说明:
*解包仅适用于方法分开接收两个定位参数的场景,例如方法定义为def click(self, by, locator):时,才需要用*把元组拆成两个参数传入。当前封装的方法是直接接收完整定位元组,无需解包。
如果需要先把定位器赋值给变量再传入,直接正常赋值即可,不需要使用星号:
# 正确的变量赋值写法 email_input_locator = SearchCustomerLocators.txtEmail_id self.click(email_input_locator)
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

