我找到了一种解决方法,可以让您在 Flutter Web 中合理自然地使用 Selenium(尽管不能与无头浏览器一起使用)
- 您需要找到窗口 x y 坐标与屏幕 x y 坐标的偏移量。我在另一个线程中发现了这个想法
pageCallibrator.html
:
<script>
window.coordinates = [];
document.addEventListener('click', function() {
window.coordinates = [event.pageX, event.pageY];
});
</script>
然后在硒中setup
运行测试之前(Java 示例)
int windowScreenOffsetX = 0;
int windowScreenOffsetY = 0;
void callibrateXY(WebDriver driver) {
driver.get("http://localhost:8080/pageCallibrator.html"); //TODO adjust host
Dimension size = driver.manage().window().getSize();
int x = size.width / 2;
int y = size.height / 2;
clickMouseAtXY(x, y);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
List<Object> coordinates = (List<Object>) ((JavascriptExecutor) driver).executeScript("return window.coordinates;");
windowScreenOffsetX = x - (int) (long) coordinates.get(0);
windowScreenOffsetY = y - (int) (long) coordinates.get(1);
}
现在在 Selenium 中按下 Flutter 按钮
WebElement continueToBankButtonElement = findElementWithText(driver, "My button text");
clickMouseAtElement(continueToBankButtonElement);
你定义的地方
import org.openqa.selenium.*
Robot robot = new Robot();
Driver driver = new ChromeDriver(options); // TODO handler exceptions and options in a method
WebElement findElementWithText(WebDriver driver, String text) {
return driver.findElement(containsTextLocator(text));
}
By containsTextLocator(String text) {
return By.xpath("//*[contains(text(), '" + text + "')]");
}
void clickMouseAtElement(WebElement element) {
clickMouseAtXY(element.getLocation().getX() + element.getSize().width / 2, element.getLocation().getY() + element.getSize().height / 2);
}
void clickMouseAtXY(int x, int y) {
moveMouse(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
/**
* @param x
* @param y
*/
protected void moveMouse(int x, int y) {
robot.mouseMove(x + windowScreenOffsetX, y + windowScreenOffsetY); // Offset of page from screen
}