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

前端 未结 10 1202
走了就别回头了
走了就别回头了 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.

    0 讨论(0)
  • 2020-11-28 11:12

    Hey you can use this for ruby

    variable.element.location_once_scrolled_into_view
    

    Store the element to find in variable

    0 讨论(0)
  • 2020-11-28 11:14

    It is actually possible to scroll automatically to element. Although this is not a good solution in this case (there must be a way to get it working without scrolling) I will post it as a workaround. I hope someone will come up with better idea...

    public void scrollAndClick(By by)
    {
       WebElement element = driver.findElement(by);
       int elementPosition = element.getLocation().getY();
       String js = String.format("window.scroll(0, %s)", elementPosition);
       ((JavascriptExecutor)driver).executeScript(js);
       element.click();
    }
    
    0 讨论(0)
  • 2020-11-28 11:16

    I posted this same answer in another question so this is just a copy and paste.

    I once had a combo box that wasn't in view that I needed to expand. What I did was use the Actions builder because the moveToElement() function will automatically scroll the object into view. Then it can be clicked on.

    WebElement element = panel.findElement(By.className("tabComboBoxButton"));
    
    Actions builder = new Actions(this.driver);
    
    builder.moveToElement(element);
    builder.click();
    builder.build().perform();
    

    (panel is simply a wrapped element in my POM)

    0 讨论(0)
提交回复
热议问题