基于页面对象模型,如何给locator.py的定位器传递变量
解决方案:将XPath定位器中的文本改为可传入变量
你可以通过以下两种方式实现动态传入附件名称的需求:
方法一:用类方法封装动态定位器(推荐)
这种方式把定位逻辑封装在locator文件中,更符合页面对象模式的设计思想,测试方法只需传入参数即可。
修改locator.py:
from selenium.webdriver.common.by import By class gm_Inbox_Locator(object): # 定义XPath模板,用占位符代替固定文本 _ATTACHMENT_XPATH_TPL = "//div[contains(@aria-label,'Press enter to view the attachment and delete to remove it')]//div[contains(text(),'{attachment_name}')]" @classmethod def get_attached_attachment_locator(cls, attachment_name): # 格式化模板,返回完整的定位器元组 return (By.XPATH, cls._ATTACHMENT_XPATH_TPL.format(attachment_name=attachment_name))
修改测试方法:
def verify_attachment_is_attached_in_compose_email(self): try: # 传入需要验证的附件名称,比如'sprint1' target_locator = self.locator.gm_Inbox_Locator.get_attached_attachment_locator('sprint1') self.wait_visibility_of_element_located(*target_locator) logging.info(f"Attachment is attached") except Exception as e: logging.error(f"Exception Occurred : "+str(e))
方法二:直接在测试方法中格式化XPath模板
如果不想修改locator的结构,可以把定位器写成带占位符的模板,在测试方法中动态替换:
修改locator.py:
from selenium.webdriver.common.by import By class gm_Inbox_Locator(object): # 保留带占位符的XPath模板 gm_Compose_email_attached_attachment_template = (By.XPATH, "//div[contains(@aria-label,'Press enter to view the attachment and delete to remove it')]//div[contains(text(),'%s')]")
修改测试方法:
def verify_attachment_is_attached_in_compose_email(self): try: attachment_name = 'sprint1' # 从模板中取出定位方式和XPath模板,替换占位符后组装成完整定位器 by_type, xpath_tpl = self.locator.gm_Compose_email_attached_attachment_template target_locator = (by_type, xpath_tpl % attachment_name) self.wait_visibility_of_element_located(*target_locator) logging.info(f"Attachment is attached") except Exception as e: logging.error(f"Exception Occurred : "+str(e))
为什么你之前的方法无效?
你直接在XPath字符串中写Attachment变量时,Python会把它当作字符串的一部分,XPath实际查找的是文本内容为"Attachment"的元素,而不是你传入的变量值,所以无法定位到目标元素。
内容的提问来源于stack exchange,提问作者AbdulQASDET
相关产品推荐
相关产品推荐

