在Appium中使用变量作为输入值的XPath或定位器可以通过以下方法解决。这是一个示例代码:
import time
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.common.touch_action import TouchAction
desired_caps = {
"platformName": "Android",
"platformVersion": "9",
"deviceName": "Android Emulator",
"appPackage": "com.example.app",
"appActivity": ".MainActivity"
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
# 等待蓝牙选择页面加载
time.sleep(5)
# 创建一个变量,用于存储要选择的蓝牙设备名称
bluetooth_device_name = "My Bluetooth Device"
# 构建XPath,使用变量作为输入值
xpath = f"//*[contains(@text, '{bluetooth_device_name}')]"
# 使用XPath来查找元素并点击
driver.find_element(MobileBy.XPATH, xpath).click()
# 停顿2秒钟,以防止后续操作太快
time.sleep(2)
# 关闭应用程序
driver.quit()
在上面的代码中,我们首先使用time.sleep()
等待蓝牙选择页面加载完成。然后,我们创建一个变量bluetooth_device_name
来存储要选择的蓝牙设备的名称。接下来,我们使用f-string来构建XPath,其中包含我们的变量bluetooth_device_name
。然后,我们使用driver.find_element()
方法和MobileBy.XPATH
作为参数来查找并点击该元素。
请注意,在使用变量构建XPath时,我们使用了contains()
函数来部分匹配元素的文本内容。这样,即使元素的文本包含其他内容,只要包含我们的变量即可找到它。
最后,我们使用time.sleep()
停顿2秒钟,以防止后续操作太快。然后,我们使用driver.quit()
关闭应用程序。