【问题标题】:How to get the x, y coordinates of an element in a web page?如何获取网页中元素的 x、y 坐标?
【发布时间】:2017-08-03 10:08:30
【问题描述】:
我正在使用 Selenium WebDriver 和 Java 编码。在代码中,我需要向下滚动到网页中的特定元素才能单击它。我正在使用 JavascriptExecutor 命令。我的问题是我将如何根据它在网页中的位置了解该特定元素的确切 x 和 y 坐标。我使用的代码语法如下:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("scroll(x,y)");
在上述代码的第二行中,我需要给出我想要点击的元素的 x 和 y 坐标的具体值。
【问题讨论】:
标签:
javascript
java
selenium
automation
【解决方案1】:
要根据网页中特定元素的像素位置了解该特定元素的确切 x 和 y 坐标,您可以考虑使用以下代码块:
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.");
}
}
确保您已导入org.openqa.selenium.Point
您的控制台上的输出将是:
Element's Position from left side is: 413 pixels.
Element's Position from top is: 322 pixels.
【解决方案2】:
我建议您参考元素本身而不是其坐标。
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
希望这会有所帮助。谢谢。
【解决方案3】:
你可以使用java selenium获取坐标,
webElement.getLocation().getX();
webElement.getLocation().getY();
【解决方案4】:
Santosh 是对的,您应该使用元素的引用进行滚动。但如果您仍然想获取坐标,请使用以下代码:-
您可以使用以下代码:-
@Test
public void getCoordinates() throws Exception {
//Locate element for which you wants to retrieve x y coordinates.
WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
//Used points class to get x and y coordinates of element.
Point classname = Image.getLocation();
int xcordi = classname.getX();
System.out.println("Element's Position from left side"+xcordi +" pixels.");
int ycordi = classname.getY();
System.out.println("Element's Position from top"+ycordi +" pixels.");
}
来源:-
http://www.maisasolutions.com/blog/How-o-get-X-Y-coordinates-of-element-in-Selenium-WebDriver