2017-08-03 179 views
0

我使用Selenium WebDriver和Java編碼。在代碼中,我需要向下滾動到網頁中的特定元素來點擊它。我正在使用JavascriptExecutor命令。我的問題是,我將如何根據它在網頁中的位置來了解該特定元素的確切x和y座標。我使用的代碼的語法下面給出:如何獲取網頁中元素的x,y座標?

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

在上面的代碼中,我需要給x和我想點擊該元素的y座標的具體數值的第二行。

+1

[檢索HTML元素的位置(X,Y)]的可能副本](https://stackoverflow.com/questions/442404/retrieve-the-position-xy-of-an-html-element) –

回答

1

我建議你引用元素本身而不是座標。

((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element); 

希望這會有所幫助。謝謝。

2

您可以使用Java硒座標獲得,

webElement.getLocation().getX(); 
webElement.getLocation().getY(); 
0

桑托斯是正確的,你應該使用滾動元素的參考。但如果你仍然想獲得的座標使用下面的代碼: -

您可以使用下面的代碼: -

@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

0

這裏回答你問題:

要知道確切的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."); 
    } 
} 

確保您已導入org.openqa.selenium.Point

您的控制檯上的輸出應該是:

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

讓我知道這個答案是否是您的問題。

+0

非常感謝DebanjanB的貢獻。非常感謝。 –

+0

@ S.Mukherjee如果我的答案滿足您的問題,請點擊答案旁邊的勾號旁邊的投票上/下按鈕接受答案。謝謝 – DebanjanB