3

I want to get the on screen coordinates of a WebElement and use the robot class to click on it.

SeleniumMethods sl= new SeleniumMethods();
WebDriver driver = new FirefoxDriver();
public void example () throws Exception{
    driver.get("http://www.example.com/");
    driver.manage().window().maximize();
    //Xpath to more Info Link
    String xpath = "/html/body/div/p[2]/a";
    Robot robot = new Robot();
    //Pass in the X and Y Coordinates of the Element (Integer)
    robot.mouseMove(driver.findElement(By.xpath(xpath)).getLocation().getX(),driver.findElement(By.xpath(xpath)).getLocation().getY());
    robot.mousePress(InputEvent.BUTTON1_MASK);
    Thread.sleep(50);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
}

It think the problem is that the coordinates passed in the mousePress method do not contain the firefox tabs,url bar etc. Is that really my problem? and if so how do I solve it? Thanks in advance!

Hills
  • 33
  • 2
  • 5
  • Possible duplicate of [Selenium: get coordinates or dimensions of element with Python](https://stackoverflow.com/questions/15510882/selenium-get-coordinates-or-dimensions-of-element-with-python) – Ywapom Aug 29 '18 at 15:00
  • after you find the element it has .size and .location properties. – Ywapom Aug 29 '18 at 15:03
  • I use the .getLocation .How can the .getSize help me? – Hills Aug 29 '18 at 16:26
  • I don't understand why you are using robot in addition to WebDriver but why don't you start splitting up the line robot.mouseMove(driver.findElement(By.xpath(xpath)).getLocation().getX(),driver.findElement(By.xpath(xpath)).getLocation().getY()); and see that you can find the element and then that the location is returned so you can get to the exact problem. – Ywapom Aug 29 '18 at 16:50
  • I did use the .getLocation and it seems like the value it returns isnt the screen dimension but the browser without the tabs and the bars – Hills Aug 29 '18 at 17:01
  • sounds like you are not getting the element you want if the elements properties are not what you expect. – Ywapom Aug 29 '18 at 17:48
  • does it work for you?have you tested it? – Hills Aug 29 '18 at 17:56

1 Answers1

1

It is not really clear to me why are you are doing what you are doing but here is a python script that gives some examples that might help

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains


driver = webdriver.Chrome()
url = "https://learn.letskodeit.com/p/practice"
driver.get(url)

el = driver.find_element_by_id("openwindow")
#in devtools you can see the elements x,y and compare to:
print("location:", el.location)
print("size", el.size)

#you can just now say el.click() but if you must move:
action = ActionChains(driver)
action.move_to_element(el) 
action.click()
action.perform()
Ywapom
  • 601
  • 5
  • 18