問題場景
構建基於selenium3的自動化平臺,添加手勢操作(TouchActions
)時發生異常,導致程序無法執行。
異常內容
org.openqa.selenium.remote.RemoteWebDriver cannot be cast to org.openqa.selenium.interactions.HasTouchScreen
項目環境
java 1.8
selenium 3.141.0
docker-selenium-chrome: 3.141.0
代碼實例
WebDriver driver = new RemoteWebDriver(webURL, cap)
TouchActions action = new TouchActions(driver);
action.build();
action.scroll(autoDriverAtion.getWebElement(), xOffSet,0).perform();
解決問題
因此,要做到這一點,首先需要將移動功能添加到驅動程序中(請參閱Mobile Emulation):
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Galaxy S5"); // Choose a device available in your version of chromimum
Map<String, Object> options = new HashMap<>();
options.put("mobileEmulation", mobileEmulation);
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
然後,當您需要觸摸操作時,就需要“增強”驅動程序,以便對其進行投射:
TouchActions builder = new TouchActions(new Augmenter().augment(remoteWebDriver));
然後,您可以從該構建器執行所需的builder.down(), move(), scroll(), up()…任何操作。
我的代碼是:
WebDriver driver = new RemoteWebDriver(webURL, cap)
TouchActions action = new TouchActions(new Augmenter().augment(driver));
action.build();
action.scroll(autoDriverAtion.getWebElement(), xOffSet,0).perform();