Having trouble scrolling with Selenium WebDriver and JavaScript Executor

Can you help me locate and click on the 5th element in this list?
The following is a list of all the rooms stored:

@FindBy(xpath="//p[@class='css-6v9gpl-Text eczcs4p0']")  
    List<WebElement> placeListings;   

Code to click on the 5th element:

public void clickon5thHouse()
    {
    Web4 = placeListings.get(4);   // **This is a list of all the web elements in <div> tag. I am selecting the 4th element from the list to click on it** 
        
        int x = Web4.getLocation().getX(); 
        int y = Web4.getLocation().getY();

        //scroll to x y 
        JavascriptExecutor js = (JavascriptExecutor) driver;
       WebDriverWait wait;
      wait = new WebDriverWait(driver,40);
      js.executeScript("window.scrollBy(" +x +", " +y +")");        
      wait.until(ExpectedConditions.elementToBeClickable(Web4));
    Web4.click();
        
    } 

Website URL:

  1. Using Chrome Browser.
  2. I have tried various scroll methods as mentioned in the commented code section.
  3. However, the scrollbar seems to reach the same point on the website for all scroll commands.

Error Logs:

org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element <p size="6" class="css-6v9gpl-Text eczcs4p0">...</p> is not clickable at point (845, 13).    
Other element would receive the click: <a data-testid="listing-details-link" href="/for-sale/details/58485081/" class="e2uk8e4 css-15tydk8-StyledLink-Link-FullCardLink e33dvwd0">...</a>

Answer №1

Here are a couple of important things to keep in mind:

  1. Don't forget about the cookie button. Make sure to select Accept all cookies to avoid any issues with scrolling.

  2. Utilize the JavascriptExecutor and Actions class

Below is an example code snippet :

driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.zoopla.co.uk/for-sale/property/london/?q=London&results_sort=newest_listings&search_source=home");
WebDriverWait wait = new WebDriverWait(driver, 10);     wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[class$='ui-cookie-accept-all-medium-large']"))).click();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0, 250)");
Actions a = new Actions(driver);
List<WebElement> allImgs = driver.findElements(By.cssSelector("a[data-testid='listing-details-image-link'] img"));
ArrayList<WebElement> allPrices = (ArrayList<WebElement>) driver.findElements(By.cssSelector("div[class*='CardHeader'] p"));
System.out.println(allImgs.size() + "and " + allPrices.size());
int i = 0;
for(WebElement e : allImgs) {
    a.moveToElement(e).build().perform();
    System.out.println(allPrices.get(i).getText());
    i++;
} 

Expected Output :

25and 32
£2,140,000
Offers in region of
£525,000
£650,000
£480,000
£270,000
Guide price
£750,000
£1,260,000
£475,000
£695,000
£450,000
£795,000
£335,000
£849,950
Offers over
£650,000
Offers over
£725,000
Guide price
£430,000
Guide price
£300,000
£520,000
£1,500,000
PASSED: testSO

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

Update 2 :

for(WebElement e : allImgs) {
    a.moveToElement(e).build().perform();
    System.out.println(allPrices.get(i).getText());
        if(i == 5) {
            e.click();
            break;
        }
    i++;
}

Answer №2

Kindly use the following line of code to assist you with your needs

driver.get("https://www.zoopla.co.uk/for-sale/property/london/?q=London&results_sort=newest_listings&search_source=home");
    
WebElement element = driver.findElement(By.xpath("(((//*[@data-testid='search-result'])[5])/div/div[2]/div[2]//following-sibling::a)"));

((JavascriptExecutor)driver).executeScript
("arguments[0].scrollIntoView(true);", element);
    
element.click();
 
customize it as necessary  

Answer №3

Finally, I have discovered the solution!

import com.zoopla.qa.base.Base;

public class propertyListing extends Base {

    static int Web4;
    @FindBy(xpath="//p[@class='css-6v9gpl-Text eczcs4p0']")
    List<WebElement> placeListings;
    List<Integer> sortedPlaceListings = new ArrayList<>();
    
    public propertyListing() throws IOException {
        PageFactory.initElements(driver, this);
    }
    
    public int getpropertyListing()
    {    
        for(WebElement e: placeListings)
        {   
            String textList = e.getText().substring(1);
            String changedText = textList.replaceAll(",", "");
            if(changedText != "POA")
            {
                sortedPlaceListings.add(Integer.parseInt(changedText));
            }
        }
        Collections.sort(sortedPlaceListings , Collections.reverseOrder()); 
        for(Integer s : sortedPlaceListings)
            System.out.println(s);
        return sortedPlaceListings.size();
    }
    public void clickon5thHouse()
    {
        Web4 = sortedPlaceListings.get(4);
         NumberFormat formatter=NumberFormat.getCurrencyInstance(Locale.UK);  
         formatter.setMaximumFractionDigits(0);
         String currency=formatter.format(Web4); 
        WebElement element = driver.findElement(By.xpath("//p[contains(text(),'"+currency+"')]//parent::div/parent::div/following-sibling::a"));
       WebDriverWait wait;
      wait = new WebDriverWait(driver,40);
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
      wait.until(ExpectedConditions.elementToBeClickable(element));
    element.click();     
    }   

}

My Testng Class

    @Test
    public void verifyHomeListings()
    {
        int countOfRooms = property.getpropertyListing();
        Assert.assertEquals(25, countOfRooms);
        property.clickon5thHouse();
    }

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

Tips for Editing and Modifying Name and Area in a Database

I'm currently working with React to develop a full CRUD application, but I'm facing challenges in updating the names and areas of rooms within houses. Any suggestions or insights on how to achieve this would be greatly appreciated. Apologies for ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

Encountering a strange issue when attempting to link app.js with mongodb

I recently set up MongoDB and the Compass, everything was working fine until I tried to connect MongoDB with my app.js. Now I'm getting a strange error message. Could anyone help me understand what this error means and how I can fix it? Unfortunately, ...

Error encountered in 11ty: Invalid operation - eleventyConfig.addPassthroughCopy is not a recognized function

Attempting to integrate my CSS and JavaScript codes into 11ty has been a bit challenging for me. I recently discovered that 11ty utilizes something called .11ty.js, so I decided to utilize the addPassthroughCopy() function. Below is the script I tried: mo ...

Dynamically uploading an HTML file using AJAX

My webpage has a feature that dynamically creates HTML with drop down elements. Additionally, there is a "create File" button on the page. The goal is for this button to trigger an AJAX POST request and upload the dynamic page created with drag and drops a ...

Tips for smoothly transitioning between tabs in IONIC by simply clicking on a link or url

Imagine having two tabs within my application: tab-one and tab-two. I am trying to navigate from the view of tab-one (one.html) to the view of tab-two (two.html). I have attempted using $state.go(), $location, and $window.location but none of them seem t ...

JQuery submitting a partial view form displays an empty page along with a JSON response

I am working on an Edit function in MVC4 public ActionResult Edit(UserGroup usergroup) { usergroup.created_date = DateTime.Now; usergroup.modified_date = DateTime.Now; db.Entry(usergroup).State = EntityState.Mod ...

What causes the function execution to not be delayed by setTimeout?

function attemptDownloadingWebsite(link) { iframe = document.getElementById('downloadIFrame'); iframe.src = link; setTimeout(removeFile(link), 25000); } This is the remove file function: function removeFile(link){ $.ajax ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

Having trouble setting up email with Passport-local. Any new suggestions?

I have been working on implementing user log-in using passport-local and express. While I have successfully managed to achieve log-ins with usernames, I find them hard to remember and not ideal for user authentication. Therefore, I attempted to customize t ...

I am currently working on creating a drag select feature in React completely from scratch, but I'm facing some challenges with

Check out this code I created for drag selection: Here's the item generation code: const items = [ 1, 2, 3, ...94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, ].map((i) => ({ item: i, selected: i === 1 })); This is the actual code responsi ...

Split the array into several arrays based on a specific threshold

I have a graph depicting an array [2,8,12,5,3,...] where the x axis represents seconds. I am looking to divide this array into segments when the y values stay 0 for longer than 2 seconds. For example, in this scenario the array would be split into 3 parts: ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

The playwright brings the curtain down on a blank page without a single word

I am working with code snippets const {chromium} = require('playwright'); (async () => { const userDataDir = '\NewData'; const browser = await chromium.launchPersistentContext(userDataDir,{headless:false}); const pag ...

Remove all of the classes from the specified element using JavaScript

I have a button and I want to remove all the classes when it is clicked. Here is what I have tried: button.style.className = '' document.querySelector('button').onclick = function() { this.style.className = ''; } .myClas ...

Encountering an issue when implementing a conditional check within the .map() function utilizing ES6 syntax

I'm struggling to assign only the object that contains an iban value to the list in the code snippet below. I haven't been able to fix this issue on my own and would appreciate some assistance. This.ibanList = this.data.map( (value, in ...

Limiting the use of JavaScript widgets to specific domains

In the process of developing a webservice that offers Javascript widgets and Ajax calls limited to specific domains, I have explored various options. However, my research has led me to consider using a combination of HTTP-Referer and API Keys for access ...

Enhance your image viewing experience with a React component that smoothly zooms in on images without distorting their dimensions, all with

After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. Th ...

The framework for structuring web applications using Javascript programming

While I have extensive experience in PHP and C# programming, my knowledge of Javascript is limited. When it comes to server side programming, MVC is my preferred method as it allows me to keep my code well-organized. However, when it comes to writing Java ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...