Selenium webdriver can't click on a link outside the page

前端 未结 10 1257
走了就别回头了
走了就别回头了 2020-11-28 10:50

I am having an issue with Selenium WebDriver. I try to click on a link that is outside the window page (you\'d need to scroll up to see it). My current code is fairly standa

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 11:11

    It might be occurring because your header element or the footer element might be blocking the view of the element you want to perform action on. Selenium tries to scroll to the element position when it has to perform some action on the element (I am using Selenium WebDriver v3.4.0).

    Here is a workaround -

    private WebElement scrollToElementByOffset(WebElement element, int offset) {
        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("window.scrollTo(" + element.getLocation().getX() + "," + (element.getLocation().getY()
                + offset) + ");");
    
        return element;
    }
    

    The above function scrolls the view to the element and then scrolls further by the offset you provide. And you can call this method by doing something like -

    WebElement webElement = driver.findElement(By.id("element1"));
    scrollToElementByOffset(webElement, -200).click();
    

    Now, this is just a workaround. I gladly welcome better solutions to this issue.

提交回复
热议问题