Having trouble selecting a dynamically changing div element in Selenium with Java using a click action

Every time I navigate to www.reddit.com and enter a query in the Search field, then press enter to go to the first valid link within a subreddit, sorting options are presented. By default, it is set to BEST but I wish to change it to TOP. My test class code is utilizing Java with BDD and POP:


public void top_most_top_tile_will_be_printed_on_screen() throws Throwable {
    redditDetailsPage.changeSorting();
}

Here is my Page code:

@FindBy (id = "CommentSort--SortPicker")
private WebElement sortingOption;
@FindBy (xpath = "/html/body/div[3]/a[2]/button")
private WebElement topOption;

public RedditDetailsPage(WebDriver driver) {
    super(driver);
}

public RedditDetailsPage changeSorting(){
    sortingOption.click();
    topOption.click();
    return this;
}

I suspect the issue lies with the xpath for the topOption element. Despite trying various methods such as locating it by parent div class or parent a class name, I consistently receive the following error message:

org.openqa.selenium.NoSuchElementException: Unable to locate element: /html/body/div[3]/a[2]/button

I attempted to use ExpectedConditions, however, it seems that my code is unable to recognize its presence. Upon clicking sortingOption.click(), this div is injected: https://i.stack.imgur.com/12bL8.png

In addition, manual testing reveals that the xpath is valid when performing the action manually and elements are highlighted. I am uncertain of other strategies to sort this list.

Could anyone advise on how to click on Sorting options and select TOP from the list using Selenium?


An interesting observation - while comparing the div obtained from manual testing, the xpath to this element was: /html/body/div[3]/a[2]/button However, upon conducting the same from debugging (when the browser from selenium was open), it pointed to: /html/body/div[4]/a[2]/button

The root cause appears to be related to the xpath, although the exact reason remains unclear. Could someone attempt this on their machines, please?

Answer №1

My suggestion is to utilize the Chropath extension for Chrome browser, which can help find suitable xpath and use it effectively.

For more information and to download, visit: https://chrome.google.com/webstore/detail/chropath/ljngjbnaijcbncmcnjfhigebomdlkcjo?hl=en

If clicking is not working, try using JavaScript as shown below:

You can use JS to perform a click action. [The method provided is for C#, but similar to Java].

 public static void scrollElementToClick(IWebDriver driver, IWebElement element)
{
    IJavaScriptExecutor ex = (IJavaScriptExecutor)driver;
    ex.ExecuteScript("arguments[0].click();", element);
}

Sometimes an element might not be clickable because it is not ready on the page. In such cases, using a wait parameter before performing a click action may help.

If you encounter issues, consider verifying the presence of the element before taking any action. The following code snippet demonstrates this approach (using C#):

 public static bool existsElement(IWebDriver _driver,By by,int waitBySecond)
    {
        WebDriverWait wait = new WebDriverWait(_driver, new TimeSpan(0, 0,waitBySecond));



        try
        {

          // wait[wait.until] for element or search element [driver.FindElement]            
        }
        catch (WebDriverTimeoutException e)
        {
            // Timeout that set for finding element        
            return false;
        }
        catch(NoSuchElementException e)
         {   
           // there is no element in this page
           return false;
         }
        catch(Exception e)
       {  return false;
       }
        return true;
    }

Q: How can I click on Sorting options and select TOP from the list using Selenium ?

A: Here are some examples of selecting options using Selenium:

         SelectElement changeOwnerMethodSelectedUser = new 
         SelectElement(_driver.FindElement(By.Name("selectedUser")));
                       // then select one choice from options by text appearance
                        changeOwnerMethodSelectedUser.SelectByText("Choice1");
                      // or you might choose by index like this [ Recommended - If you want to select choice by Top option]
                          changeOwnerMethodSelectedUser.SelectByIndex(3);

Note: These code snippets are written in C#. Adjust the syntax accordingly when testing in Java.

Answer №2

To adjust the sort options to display the top results, you can utilize the selectors provided below:

@FindBy (id = "search-results-sort")
private WebElement sortingOption;

//@FindBy (xpath = "//a[.='Top']/button")
@FindBy (css = "a[href*='sort=top']")
private WebElement topOption;

public RedditDetailsPage(WebDriver driver) {
    super(driver);
}

public RedditDetailsPage modifySorting(){
    sortingOption.click();
    topOption.click();
    return this;
}

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

adjusting the dimensions of images to ensure uniformity in size

After many attempts, I am still struggling to resize my image. Can anyone offer assistance? I want all images to have the same dimensions. Here is the HTML code: <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='sty ...

Issue encountered when sending information to asmx web service via ajax and displaying the result on an HTML page with a javascript function

I have developed an ASMX web service that looks like this: [ScriptService] public class CurrencyData : System.Web.Services.WebService { [WebMethod] public string DisplayCurrency(double amount, string sign ,string style) { swi ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Interacting with a PNG file using a border radius in Internet Explorer 9 is causing issues with its transparency

Encountering an issue with IE9 where a white to gray gradient box appears around the transparent PNG on hover/selection. There is also a border radius applied to the thumbnail. Any ideas on how to fix this problem? Here is an example of the issue: https ...

React - z-index issue persists

My React App with Autocomplete feature is almost complete, but I need some assistance to double-check my code. https://i.stack.imgur.com/dhmck.png In the code snippet below, I have added a search box with the className "autocomplete" style. The issue I a ...

How does Java compare to PHP's list() function when it comes to accessing variables in an array?

How can you achieve a similar functionality to PHP's list() function in Java? Consider the following example: $matches = array('12', 'watt'); list($value, $unit) = $matches; ...

The animation on my jQuery script seems to be malfunctioning

I'm encountering an issue with a div element that is partially off the screen and should move out when a button is clicked. I've shared my script here, but it seems to not work as intended when the button is pressed. The visualization in jsfiddle ...

The CSS transition feature does not seem to be functioning properly when it comes to displaying

In my Next.js application, I am using a card component with a "read more" link that should expand the card when clicked. To achieve this behavior, I integrated the "react-show-more" library from https://github.com/One-com/react-show-more. I tried to add ...

Keywords: <footer>, <aside> not encompassing all aspects of the HTML on the content page

Recently, I have been transitioning my codebase from .NET webform to .NET Core: In the _Layout.cshtml, elements like <hr> and <section> span the entire width (e.g. 100%) of the html page as expected. However, when I insert similar tags in the ...

Tips for adjusting alignment in MaterializeWould you like to change the alignment

I have implemented the Materialize framework for my front-end design. Initially, everything looks good when the page loads, but upon returning to the index, there is an alignment issue. Clearing the cookies seems to fix it. Here is how it currently looks: ...

spark of unique substance

Having trouble with cycle2 as all images are briefly displayed when the page loads. I tried the recommended solution http://jquery.malsup.com/cycle/faq.html but it didn't stop the flashing, indicating a different issue: The suggested fix for Cycle is ...

Ajax is functioning properly on Internet Explorer and Safari, however it is not functioning on Firefox, Chrome, or Opera

I am attempting to retrieve modal data from an HTML page using jQuery Ajax. It seems to be functioning properly in Safari and IE 6, however I'm encountering issues in Firefox, Chrome, and Opera. Any suggestions on how to resolve this? You can find my ...

Attempting to align content in the middle of the page across all web browsers

I need assistance with centering all the content on my website across different screen sizes and browsers. Currently, everything appears off-center and aligned to the left on various screens I have tested. You can view the HTML and CSS code in this link. H ...

Tips for preserving Firefox webdriver session in Python

In order to preserve the chromedriver session, I implemented this code snippet: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('user-data-dir= path to where to save sessi ...

Display a DIV next to the mouse cursor when a span is hovered over

Is there a way to make a DIV element appear at the mouse cursor when a user hovers over a SPAN or another DIV? I attempted to create a function for this purpose, but unfortunately, it does not seem to be working properly even though jQuery is correctly lo ...

Tips for passing a page as an argument in the function parameter of the page.evaluate() method?

I keep running into this issue when I pass the page as an argument: TypeError: Converting circular structure to JSON --> commencing at object with constructor 'BrowserContext' | property '_browser' -> object with const ...

Exporting Python Pandas Data Frame to an HTML file

I'm attempting to save a Python Pandas Data Frame as an HTML page. I also want to ensure that the table can be filtered by the value of any column when saved as an HTML table. Do you have any suggestions on how to accomplish this? Ultimately, I want t ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

Alert popup onclick feature is malfunctioning

SOLVED: I finally figured out the issue and it is now working perfectly. I had to manually switch to Chrome instead of using the Brackets live viewer. I want an alert box to pop up when the "Home" link is clicked on my website. I tried creating a separate ...

Preventing chromedriver from taking focus on Ubuntu 16.04 LTS with Selenium

My selenium script is designed to scrape a website. However, I am facing an issue where each time the script opens a new link, Google Chrome launches a new window and takes focus away from other open windows on my Ubuntu 16.04 LTS system. I have attempted ...