gpt4 book ai didi

javascript - 如何获取网页中元素的x,y坐标?

转载 作者:行者123 更新时间:2023-11-29 16:05:06 24 4
gpt4 key购买 nike

我正在使用 Selenium WebDriver 并使用 Java 进行编码。在代码中,我需要向下滚动到网页中的特定元素以单击它。我正在使用 JavascriptExecutor 命令。我的问题是如何根据该特定元素在网页中的位置了解该特定元素的确切 x 和 y 坐标。我使用的代码语法如下:

JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("scroll(x,y)");

在上面代码的第二行我需要给出我想要点击的元素的x和y坐标的具体值。

最佳答案

要根据该特定元素在网页中的像素位置了解该特定元素的确切 xy 坐标,您可以考虑使用以下代码块:

import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class location_of_element
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in");
WebElement element = driver.findElement(By.name("q"));
Point point = element.getLocation();
System.out.println("Element's Position from left side is: "+point.getX()+" pixels.");
System.out.println("Element's Position from top is: "+point.getY()+" pixels.");
}
}

Ensure that you have imported org.openqa.selenium.Point

控制台输出如下:

Element's Position from left side is: 413 pixels.
Element's Position from top is: 322 pixels.

关于javascript - 如何获取网页中元素的x,y坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481118/

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