Instructions for accessing and printing text from a nested ul tag with Selenium in Java

Hello everyone, I am currently learning about Selenium Automation and have created a website as shown below. Here is the HTML code:

<!DOCTYPE html>
<html>
<head><title>Shop</title></head>
<body>
<ul>
    <li><a href="www.rendertofruitsection.com">Fruits</a>
       <ul>
           <li><a href="www.addbananatocart.com">» Banana</a></li>
           <li><a href="www.addappletocart.com">» Apple</a></li>
           <!--List goes on-->
       </ul>
    </li>
    <li><a href="www.redertovegsection">Vegetable</a>
         <ul>
              <li><a href="www.addcapcicumtocart">» Capsicum</a></li>
              <li><a href="www.addtomatotocart.com">» Tomato</a></li>
              <li><a href="www.addoniontocart">» Onion</a></li>
              <!--List goes on-->
         </ul>
    </li>
    <li><a herf="www.nonveglink.com">Non Veg Section</a></li>
    <!--List goes on-->
</ul> 
</body>
</html> 

Initially, my goal was to extract all the text inside the <a> tag using Java Selenium. Here is the Java code I used:

public class shop {
    public static void main(String[] args) {
        WebDriver driver= new ChromeDriver();
        driver.get("www.myshopping.com");
        List<WebElement> text =  driver.findElements(By.xpath("//a"));
        for(int i=0; i<text.size(); i++) {
             System.out.println(i + ". " + text.get(i).getText());
        }
    }
}

The output I received did not include the nested <ul> tags and their <li> items. Can someone provide me with a hint on how to achieve this in Selenium Java?

I attempted some solutions but got stuck at this point. Any help or guidance would be greatly appreciated. Thank you!

Answer №1

If you want to extract all the text content within the <a> tag, you can use the code snippet provided below:

public class Store
{
    public static void main(String[] args)
    {
    WebDriver browser= new ChromeDriver();
    browser.get("www.myshopping.com");
    List<WebElement> links =  browser.findElements(By.tagName("a"));
    for(WebElement link:links)
         System.out.println("Text inside link : " + link.getAttribute("innerHTML"));
    }
}

Answer №2

WebElement element = driver.findElement(By.xpath("xpathOfTheElement"));
String content = element.getAttribute("innerText");
System.out.println(content);

Answer №3

Consider implementing an outer loop for item types and then incorporate an inner loop for items that are appearing to be dynamically generated:

public class store {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("www.myshopping.com");
        List<WebElement> text = driver.findElements(By.xpath("//li[ul]/a"));
        
        for (int i = 0; i < text.size(); i++) {
            System.out.println(i + ". " + text.get(i).getText());
            WebDriverWait wait = new WebDriverWait(driver, 10);
            List<WebElement> innerText = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(".//following-sibling::ul//a[text()]")));
            
            for (int j = 0; j < text.size(); j++) {
                System.out.println(i + ". " + j + ". " + text.get(j).getText());
            }
        }
    }
}

Answer №4

To only target the elements within the outer ul, you can modify the code as shown below. Simply update the locator:

public static void main(String[] args) {
       WebDriver driver= new FirefoxDriver();
       driver.get("file:///C:/Users/abdul%20awal/Desktop/test.html");
       List<WebElement> text=  driver.findElements(By.cssSelector("ul ul a"));
       for(int i=0;i<text.size();i++)
       {
            System.out.println(i+". "+text.get(i).getText());
       }
   }   

To learn more about CSS selectors, visit this link:

https://www.w3schools.com/cssref/css_selectors.asp

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

Can you explain the purpose of 'service_args' in the selenium-python chrome webdriver?

My quest for information on the service_args argument for the chrome webdriver led me to various pages like this one and that one, but unfortunately they did not provide the answers I was looking for. Now I'm left wondering: where can I find reliable ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...

Is there a way to adjust the input type date format to show mm/dd/yy?

My input type is set to "date" with the default format of mm/dd/yyyy. However, I would like to change it to mm/dd/yy. Is there a way to adjust the format of a date input? Date: <input type="date" id="date" name="date" value="mm/dd/yy" required/> ...

What is the proper method for attempting to implement Response.Redirect?

Is there a better way to handle redirect failures than using a try-catch block? Typically, a redirect always throws an exception which can be caught as a ThreadAbortException. However, is this the most effective approach? EDIT: My goal is to redirect to ...

Displaying and Concealing Table Rows using Javascript

I am working with an array of prices that are being displayed in a table using a foreach loop. The goal is to hide specific rows in the table based on certain conditions. The $status variable is set to "YES" if the price is => 30, and "NO" if the price ...

When implementing flex-grow 1 on a flex box, the remaining space is not being filled as expected

I am struggling to make the green div fill the remaining space of a flex box container. My goal is to have the top row (blue) adjust its height based on content, and then have the row below (green) take up the rest of the space. However, it seems like the ...

Adjust the Bootstrap settings to center the title on the navbar and shift the logout button to the right side

Is there a way to centrally align the title "My project" in the navbar while also keeping the logout button on the right of the same line as the title? <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="contain ...

Displaying recorded information from PHP/MySQL dropdown menu

My never-ending problem requires a simple solution. Despite searching online and in books, I can't seem to crack it. My goal is to display results from a drop-down menu that is currently connected to a database/table and showing the l_state as require ...

Using Selenium Webdriver to set a cookie with a Chrome extension

I have been experimenting with a Chrome extension in order to set a cookie when I use a Selenium Webdriver instance to open a page. Despite trying various methods suggested on different Stack Overflow posts, none of them seem to work as the cookie does not ...

What's the best way to undo a CSS transition animation when deleting an active class?

I'm currenty working on a straightforward icon animation within a VueJS application. I've implemented a Vue transition to create a fade effect on the background elements, but I'm exploring options for a subtle upward shift animation specific ...

Header escapes div and continues to move

I am currently working on building a website. One of the key features I want to include is a fixed top bar that remains visible at all times. In this bar, I have added buttons, an image, and a headline. However, I am facing an issue where the headline keep ...

Ways to align the icon and text to the left side of the screen?

I am looking to utilize Bootstrap's list group feature to create a navigation bar similar to the image below: https://i.sstatic.net/bndVl.png I am curious about how I can shift them to the left. Here is what I have attempted so far. .list-group-i ...

Trouble with Div Display

I have a section below my form that will show an alert message if there is an error. The issue I am facing is that if I use the inline-block property, everything within the section will be displayed in the alert color. I specifically want the background- ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

Configuration for running Browserstack with parallel OS testing using WebdriverIO

I need to run a series of test suites on both Mac OS and Windows OS across Chrome, Firefox, Safari, and Internet Explorer. While I have parallel testing set up for browsers, I am struggling to incorporate the OS flag into this process. My current approach ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

What is the reason behind the jQuery only functioning properly on Internet Explorer 8 on this particular page and no other browsers?

I recently created a webpage utilizing jQuery: The functionality on the page should change music images to represent different key signatures when switching from 'Higher Key' to 'Lower Key' in the combo box. While this works perfectly ...

divs placed next to each other

I'm facing an issue with 4 divs within a parent div. I've used float:left in the style of all 4 divs to display them side by side. Although the divs are appearing next to each other, the height of the parent div is not adjusting to accommodate th ...

Forming triangles with outlines

Recently, I had the challenge of designing speech bubbles and found a clever technique to create the triangular tip at the end using CSS. By setting the element's width and height to 0 and playing around with borders, you can achieve diagonal shapes f ...

To enhance user experience, consider incorporating a 'Next Page' feature after the completion of every four paragraphs,

Here is a code snippet that can be used to print 'n' number of paragraphs: <% while(rs.next()){ String para=rs.getString("poems"); %> <p> <%=para%> </p> <!-- n number of p tags are printe ...