Retrieve the content from the specified element

I need to extract the text from the span element ( Afghanistan ), but when I try using the path for the span (

//span[@class=‘mat-option-text’]
), it also includes the text from the mat-icon ( warning ).

The current output displayed in the console is:

Afghanistan warning

Is there a way to only print Afghanistan without the additional text?

https://i.sstatic.net/LHKHa.png

Answer №1

The country known as Afghanistan is mentioned in a text node. In order to extract this information, you will need to utilize WebDriverWait for the method visibilityOfElementLocated() and you have the option of using different Locator Strategies:

  • cssSelector:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span.mat-option-text")))).toString());
    
  • xpath:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='mat-option-text']")))).toString());
    

Answer №2

To successfully run JavaScript, follow these steps:

Ensure you have the necessary 'WebElement' and 'JavascriptExecutor' objects set up in your code.
Use the 'driver.findElement(By.className("mat-option-text"))' method to locate the specific element on the webpage.
Create a 'JavascriptExecutor' object by casting it to the 'driver'.
Retrieve the text content of the 'span' element using the 'executeScript' method with the specified script.

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 on displaying data in pie chart legend using react-chartjs-2

I am currently using a pie chart from react-Chartjs-2 for my dashboard. The requirement is to display both the label and data in the legend. I have implemented the following component in my application: import React, { Component } from "react"; ...

What are the methods to determine if vue-router is being utilized within the present Vue instance?

I am working on creating a library that includes a vue.js component with navigation elements. The goal is for this component to be flexible, able to function both with and without vue router. When used with the router, it will utilize <router-link> ...

Finding checkboxes that have the "checked" attribute: a simple guide

I'm working with a list of checkboxes and trying to identify the ones that have the "checked" attribute. Here's an example of what my checkbox element looks like: <input type="checkbox" class="u-display--inline-block u-margin-right--small" ch ...

Obtain a specific text value as a variable using Google Tag Manager

In my quest to extract the dynamic "sku" value from GTM, I am faced with a challenge. This particular value is unique for each product page. Below is an example of how the code appears on the page: <script type="application/ld+json"> { "@context" ...

.eslintignore not functioning as intended

Recently, I started working on a Vue template project that includes ESLint. However, I found that I wanted to disable ESLint for some reason. To do this, I followed the recommended steps and created a file with the following content: **/*.js This file wa ...

Sending a json array from PHP

I spent several hours searching for solutions to my problem but couldn't find an answer. I'm trying to perform a search on the same page using jQuery, AJAX, and PHP. Unfortunately, the array from PHP is still returning undefined. Here is the P ...

Python code to asynchronously make HTTP requests to multiple URLs and retrieve the responses

I'm dealing with a situation where I have over 500 URLs and extracting their HTML code is taking too long. Is there a way to download them asynchronously for faster processing? Code: from selenium import webdriver from selenium.webdriver.firefox.optio ...

Is there a more efficient method for creating HTML with coffeescript / jQuery besides using strings?

Today marks my first attempt at creating a "answer your own question" post, so I hope I am on the right track. The burning question in my mind was, "Is there a more efficient way to generate HTML with jQuery rather than using tag strings?" My goal is to c ...

Using Capybara for testing integration with asynchronous JavaScript

I am currently facing an issue with a failing Rails integration test that has me stumped. The test utilizes Capybara with Selenium as the driver. The specific problem lies in verifying that certain page content is removed after an AJAX call is made. Essen ...

PHP session does not refresh

There seems to be an issue occurring with my session. Here is the PHP code snippet I have been testing: public function updateTable() { $data = $this->getData(); $json_data = array( "recordsTotal" => intval($data[' ...

Unable to interact with button using Selenium automation framework

Having difficulty with clicking on the "next" button found in this page: Attempts have been made using xpath, css_selector, but without success. Here is the code snippet: try: next_page = driver.find_element_by_xpath('//*[@id="collapseOn ...

Developing AJAX Post Functionality Using Only Vanilla Javascript

Can I achieve AJAX Post in Pure Javascript without using the xmlhttprequest object? Consider a basic form like this: <form action="request.php" id="register_form"> <input type="text" name="first_name" placeholder="First Name"> <input t ...

reactjs error: Attempting to utilize the toLowerCase method on an undefined property during double mapping

My issue involves a JSON structure that requires mapping a function twice in a loop to access objects within an array. Once mapped, I need a textbox for searching the data list. However, I am encountering the following error: TypeError: Cannot read proper ...

A step-by-step guide on summoning a TimePicker from a DialogFragment

Imagine I have a Fragment with a button labeled "Settings". Once the user clicks on this button, a DialogFragment named "Settings" pops up. Now, from this "SettingsDialogFragment", I need to activate a TimePicker, which is another DialogFragment. Is ther ...

Running code concurrently in JavaScript

Currently, I am in the process of learning Angular.js and decided to create my own authentication code using a REST-like API. Below you can find the implementation of my authentication service. The main issue with my signIn function is that it consistentl ...

Is it acceptable to generate a React Element from another Element in ReactJs?

One time, I came across a code that looked like this: var App = <div> Hello World </div>; ReactDOM.render(<App />, <selector>) Surprisingly, it was working perfectly fine. However, I couldn't grasp what was actually happening ...

Encountering a snag when trying to grant notification permission in the Expo app

I am experiencing an issue with a simple code that previously asked for notification permissions. However, I am now encountering the following error: "Error: Encountered an exception while calling native method: Exception occurred while executing exp ...

What is the mechanism by which sending data directly to the response object displays content to the user?

What exactly does the .pipe(res) segment of the code snippet from that article do at the end of the stream? fs.createReadStream(filePath).pipe(brotli()).pipe(res) I have a basic understanding that the first part reads the file and the second compresses i ...

The sign-up modal will refresh and then close when an API call is triggered upon submission in Next.js

Within my modal component, I have incorporated a feature that displays either a sign-in or sign-up form based on certain conditions. However, I am facing an issue where upon clicking the submit button on any of these forms, the modal closes regardless of t ...

Step-by-step guide to extracting text using xpath

Hello everyone As a 15-year-old, I am currently in the process of creating a Python/Selenium script that automatically logs into my school's webpage to check for upcoming homework assignments. I have set up the script to detect homework based ...