Selenium WebDriver获取元素SCREEN坐标

时间:2018-08-29 14:22:33

标签: java selenium-webdriver point awtrobot

我想获取WebElement的屏幕坐标,并使用机械手类单击它。

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);
}

它认为问题在于在mousePress方法中传递的坐标不包含Firefox选项卡,URL栏等。这真的是我的问题吗?如果可以,我该如何解决? 预先感谢!

1 个答案:

答案 0 :(得分:0)

对我来说还不是很清楚,你为什么要做什么,但这是一个python脚本,其中提供了一些可能会有所帮助的示例

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()