PyQt5结合Appium:如何获取控件文本内容?
解决PyQt5 GUI在Appium中获取控件显示文本的问题
我之前也遇到过类似的困扰,PyQt控件的显示文本在Appium里默认不会直接通过.text返回,这是因为Appium对Qt辅助功能属性的映射有特定规则。你现在拿到的是控件的accessibleName(也就是你设置的"errorMsg"),而非实际显示的文本,核心原因是没有把控件的显示文本暴露给辅助功能框架。
下面给你两种可行的解决方案:
方案1:设置控件的accessibleText属性
PyQt控件提供了setAccessibleText()方法,专门用来设置控件的可访问文本(这是辅助功能框架识别控件内容的关键属性)。你只需要在动态设置控件文本时,同步设置这个属性即可:
修改你的login_function代码:
def login_function(self): user = self.emailField.text() password = self.passwordField.text() if len(user) == 0 or len(password) == 0: msg = "Please input all fields." self.errorMsg.setText(msg) self.errorMsg.setAccessibleText(msg) # 同步设置可访问文本 else: conn = sqlite3.connect(shop_data) cur = conn.cursor() query = f"SELECT password FROM login_info WHERE username = '{user}' " cur.execute(query) try: result_pass = cur.fetchone()[0] if result_pass == password: print("Successfully logged in") msg = "" self.errorMsg.setText(msg) self.errorMsg.setAccessibleText(msg) # 同步清空可访问文本 else: msg = "Invalid username or password" self.errorMsg.setText(msg) self.errorMsg.setAccessibleText(msg) # 同步设置可访问文本 except TypeError: # 处理用户不存在的情况(fetchone()返回None) msg = "Invalid username or password" self.errorMsg.setText(msg) self.errorMsg.setAccessibleText(msg) finally: conn.close()
然后在Appium测试代码中,通过get_attribute("accessibleText")获取实际文本:
def testLoginFailure(self): self.driver.implicitly_wait(10) self.driver.find_element_by_name("login").click() self.driver.find_element_by_name("username").send_keys("marysmith") self.driver.find_element_by_name("password").send_keys("123456") self.driver.find_element_by_name("loginPageLogin").click() error_element = self.driver.find_element_by_name("errorMsg") self.assertEqual(error_element.get_attribute("accessibleText"), "Invalid username or password")
方案2:用Appium Inspector确认控件属性
如果你不确定哪个属性对应显示文本,可以用Appium Inspector连接到你的应用,定位到errorMsg控件后查看所有属性列表。通常Qt控件的显示文本会出现在text或accessibleText属性中,找到对应属性名后用get_attribute()获取即可。
补充说明:为什么之前的.text返回控件名?
因为你给控件设置了accessibleName为"errorMsg",而当控件未设置accessibleText时,Appium会默认将accessibleName作为元素的.text属性返回,这就是你拿到"errorMsg"而非实际提示文本的原因。
内容的提问来源于stack exchange,提问作者Woden
相关产品推荐
相关产品推荐

