gpt4 book ai didi

javascript - 如何通过图像查找元素

转载 作者:行者123 更新时间:2023-12-02 09:45:52 25 4
gpt4 key购买 nike

据我们所知,selenium支持多个定位器策略来查找网页上的元素。

但我的要求不同,我有一些网站,其中 selenium 支持的任何定位器都不足以唯一地找到元素。

由于selenium提供了创建自己的自定义定位器策略来查找元素的设施,我正在尝试创建图像定位器,它可以使用base64 String查找元素像 appium 一样的子图像。

图像定位器积分:

  1. 使用 URL 启动浏览器
  2. 捕获页面屏幕截图
  3. 从屏幕截图中检测子图像的xy位置
  4. 使用页面中的xy位置查找元素

为了完成此任务,我正在创建自定义 Image 定位器,如下所示:

public class ByImage extends By {

String imageBase64String

/**
* @param imageBase64String
*/
public ByImage(String imageBase64String) {
this.imageBase64String = imageBase64String
}

@Override
public List<WebElement> findElement(SearchContext context) {
List<WebElement> els = findElements(context)
if (els) {
return els.get(0)
}
throw new NoSuchElementException("Element not found")
}

@Override
public List<WebElement> findElements(SearchContext context) {
//Get current screenshot
byte[] screenshotByte = ((TakesScreenshot)context).getScreenshotAs(OutputType.BYTES))
byte[] subImgToFindByte = DatatypeConverter.parseBase64Binary(imageBase64String)
//Convert buffred image to get height and width of subimage
BufferedImage bufferedSubImgToFind = ImageIO.read(new ByteArrayInputStream(subImgToFindByte ));

//Here I need a mechanism to get coordinates of sub image from screenshot
//Suppose I able to find x, y
double x
double y

//Now find element using coordinates
//Now calculate center point
int centerX = int(x + (bufferedSubImgToFind.getWidth() / 2))
int centerY = int(y + (bufferedSubImgToFind.getHeight() / 2))

JavascriptExecutor js = ((JavascriptExecutor)context)

return js.executeScript("return document.elementsFromPoint(arguments[0], arguments[1]);", centerX, centerY)
}
}

现在测试用例如下:

WebDriver driver = new ChromeDriver()
driver.get("<URL>")
WebElement elementByImage = driver.findElement(new ByImage("<Base64 String of the subimage>"))

我能够实现一切,除了一个更好的库来从 subimage 检测 image 的精确坐标以使用坐标查找元素。

有人可以建议我更好的方法来完成这项任务吗?

最佳答案

您可以选择不同的选项,例如:

  1. 您可以使用Java Bindings for OpenCV为了查找主屏幕截图中的子图像,请查看 Template Matching文章提供全面的解释和代码片段。
  2. Project Sikuli提供一些简单的图像识别/交互API
  3. SeeTest Automation提供图像识别和Object Repository图像模板的模式实现

关于javascript - 如何通过图像查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com