Clicking at coordinates without identifying element

前端 未结 14 1898
醉酒成梦
醉酒成梦 2020-11-28 07:49

As part of my Selenium test for a login function, I would like to click a button by identifying its coordinates and instructing Selenium to click at those coordinates. This

相关标签:
14条回答
  • 2020-11-28 08:20

    There is a way to do this. Using the ActionChains API you can move the mouse over a containing element, adjust by some offset (relative to the middle of that element) to put the "cursor" over the desired button (or other element), and then click at that location. Here's how to do it using webdriver in Python:

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    browser = webdriver.Chrome()
    elem = browser.find_element_by_selector(".some > selector")
    ac = ActionChains(browser)
    ac.move_to_element(elem).move_by_offset(x_offset, y_offset).click().perform()
    

    Y'all are much to quick to dismiss the question. There are a number of reasons one might to need to click at a specific location, rather than on an element. In my case I have an SVG bar chart with an overlay element that catches all the clicks. I want to simulate a click over one of the bars, but since the overlay is there Selenium can't click on the element itself. This technique would also be valuable for imagemaps.

    0 讨论(0)
  • 2020-11-28 08:20
        WebElement button = driver.findElement(By.xpath("//button[@type='submit']"));
        int height = button.getSize().getHeight();
        int width = button.getSize().getWidth();
        Actions act = new Actions(driver);
        act.moveToElement(button).moveByOffset((width/2)+2,(height/2)+2).click();
    
    0 讨论(0)
提交回复
热议问题