Guide on how to navigate to the bottom of a div element using Selenium Webdriver

My current project involves a unique challenge where there is a specific div element on the webpage that acts as a popup dialog when a link is clicked (similar to Facebook reaction dialog boxes).

To automate tests for this scenario, I am using Selenium WebDriver with Java. The task at hand requires me to scroll to the bottom of the dialog box where there is a "Show More" link. Clicking this link loads an additional 10 items in the list, and this process continues until all items have been displayed.

The challenge lies in continuously scrolling down within that specific div element to locate the "Show More" link. If the driver cannot find the link, the scrolling should stop.

It is important to note that a simple JavaScript `window.scrollTo()` function cannot be used to scroll to the bottom of the whole page; rather, the goal is to scroll only within that particular division element.

If anyone has any suggestions or solutions on how to achieve this step-by-step scrolling within the div element, please share your insights.

Thank you in advance for your assistance!

Answer №1

A different method for navigating to the bottom within a scrollable container:

function scrollToBottomInsideElement(element) {
    const jsExecutor = (JavascriptExecutor) driver;
    jsExecutor.executeScript("arguments[0].scrollTo(0, arguments[0].scrollHeight)", element);
}

Answer №2

WebElement elementToScroll= driver.findElement(By.id("id_of_element"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", elementToScroll);

or

WebElement elementToClick= driver.findElement(By.id("id_of_element"));
Actions actions = new Actions(driver);
actions.moveToElement(elementToClick).click();
Action actionPerform=actions.build();
actionPerform.perform();

Answer №3

I encountered a similar issue and managed to resolve it by referencing a question on SQA SO. You can find the helpful post here.

Take a look at the final answer provided by Sagar007, who implemented a separate function scroll_Page() to address this issue.

The code snippet below is directly from his solution:

Some HTML pages have custom internal scroll bars that require a different approach. Javascript may not be effective in these cases.

Solution :

WebElement scrollArea = 
driver.findElement(By.cssSelector("div.slimScrollBar"));

In my implementation, I included an additional step of clicking on the div element using the click() method before proceeding further.

To create the scroll_Page method as outlined below and invoke it as required.

 scroll_Page(scrollArea ,100);

Where scrollArea represents the element to be scrolled and 100 indicates the number of scroll points.

  public static boolean scroll_Page(WebElement webelement, int scrollPoints)
{
try
{               
    Actions dragger = new Actions(driver);
    // drag downwards
    int numberOfPixelsToDragTheScrollbarDown = 10;
    for (int i = 10; i < scrollPoints; i = i + numberOfPixelsToDragTheScrollbarDown)
    {
        dragger.moveToElement(webelement).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release(webelement).build().perform();
    }
    Thread.sleep(500);
    return true;
}
catch (Exception e)
{
    e.printStackTrace();
    return false;
}

Answer №4

In order to achieve scrolling functionality for a dynamically loaded div on a webpage, I utilized a Java function that was called within a while(someCondition()) loop. The approach involved incrementing the scroll value by 1000 units each time the function was triggered.

private int scroll;
private void scrollDownPopup() {
    scroll += 1000;
    JavascriptExecutor jse = (JavascriptExecutor) browser;
    // To determine the query selector for the specific div element, use an inspector tool
    jse.executeScript("document.querySelector('body > div.Blah.Blah1 > div > div.ClassOfYourDiv').scrollTo(0, " + scroll + ");");
}

Answer №5

One useful method to utilize is scrollIntoView

Comparing scrollIntoView and moveToElement Understanding the difference between scrollIntoView and moveToElement

Ensure that you pass the link element for "more items" as an argument.

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

Another option is to use moveToElement

Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Answer №6

To reach the bottom of a specific element by scrolling, one can employ the following method:

public void goToBottomOfElement(WebElement target) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].scrollIntoView({block: 'end'})", target);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing LocalStorage in conjunction with the redux state management

Currently, I am working on a single-page application using React and Redux. I have encountered the need to store certain data locally and ensure that it remains synchronized with the appState in local storage, even after a page refresh. Despite being new ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

What is the proper way to incorporate an apostrophe (') within an XPath expression when locating an element with webdriver

When working with webdriver to find elements, I encounter a need to use an apostrophe (') in my xpath expression. Here is the xpath expression that I need to use: //input[@text="WE'd like to hear from you"] To incorporate this expression into ...

Guide on loading xml information from a web browser using JavaScript

I have been working on loading data from the browser using a URL and currently utilizing JavaScript to achieve this. window.onload = function() { // This is the specific URL I am attempting to load data from. // The XML fi ...

Selenium-Web Driver encounters an issue with reading the 'filter' property as undefined

Recently, I started working with Selenium and encountered an issue while trying to wait for a specific element to load. The error message that popped up was: (node:8472) UnhandledPromiseRejectionWarning: NoSuchElementError: no such element: Unable to ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Trouble retrieving data (React-redux)

Greetings! I am currently working on a project involving the Spotify API and attempting to retrieve new releases. While the data is successfully passed down to the reducer, I encounter an issue when calling the fetch action in my App component. When I try ...

What is the best way to create a select box in React that allows for both single and multiple selections?

I recently started utilizing a new package for generating dynamic forms, which can be found at this link. Upon reading through the documentation, I attempted to create a select box as outlined in the instructions provided here. Despite following the step ...

How to utilize Safari driver in Selenium for positioning images

I'm attempting to capture a screenshot of a webpage, extract the size and position of an image, and then save that image to a file. Here is a snippet of code: this.driver.navigate().to(xxx); final byte[] arrScreen = ((TakesScreenshot) this.driver). ...

Tips for making a Scroll Button

I am in the process of designing a horizontal website and I would like to incorporate two buttons, one on the left and one on the right, that allow users to scroll to the left and right, respectively. You can check out the site I am currently working on h ...

Hover over the image with some padding placed around it to see

I am struggling to figure out how to add padding to my image when hovering over it with Onmouseover. I have tried multiple solutions but none seem to be working. Here is the original code: <img src='/wp-content/uploads/2015/04/img-white.png' ...

When the section comes into view on the screen, the CSS animation will play only one time

While browsing through , I found some fantastic animations that inspired me. The animations at the header seem to be standard CSS animations with delays. However, as you scroll down and other sections become visible, the animations reappear only once. Can ...

I'm struggling with developing react applications due to problems with canvas elements

I am currently using an M1 MacBook Pro, with Node version 15.4.1 and npm version 7.0.15. When I ran the command npx create-react-app my-app, it gave me this output: I have attempted various solutions but keep encountering the same issue related to "canva ...

Various options can be chosen to alter the margin

$('#cpseltop').change(function() { var a = $(this).val(); $('.cpselhide').hide(); $('#cpsel' + a).show(); }); .cpselect{ display:block; border:1px solid #999; border-radius:9px; outline:none; width:100%; padding:2px 5px; curso ...

Tips for assigning data from an AJAX response to a variable

Using jQuery and the code provided, there seems to be an issue with variable scope when some_condition is false. The error "items is not defined" indicates this problem. The goal is to set the result variable to the AJAX response data in order to use it o ...

Renaming the screenshot file stored in the /img directory within the QAF framework

I'm facing a requirement where I need to include a time stamp for the screenshot images saved in the /img folder. Upon inspecting AssertionService.java at this link, it seems that a random string is being added at the end of the file name. Can someon ...

Updating a nested subarray using Node.js with the MongoDB API

I am currently in the process of developing a backend API using Node.js/Express and MongoDB for managing student records. I am facing difficulty with updating a sub-field within the data structure. Below is the code snippet from my Student.js file located ...

Modify JSON from using single quotes to double quotes using JavaScript

Received a JSON from the backend to the front end that uses single quotes throughout, causing issues with a Magento 2 widget. The JSON structure is as follows: { 'mood': 'happy', 'reason': 'why shouldn't I?'} T ...

Tips for passing Selenium choices as a data structure within Robot Framework sans stumbling upon the 'AttributeError: 'list' object lacking the 'capabilities' attribute' error

My goal is to utilize a data structure for transferring options to the Selenium Open-browser interface. The library's documentation indicates that it accepts type 'Any', suggesting that a list, dictionary, or any combination should be permi ...

The AJAX email submission form is not functioning properly

Recently, I have upgraded my email sign-up form on the website to include validation. However, after adding the validation, the form no longer sends and an error message is not displayed. Upon inspecting, I found the following error: TypeError: null is ...