Finding a way to extract a singular text node after the Span element but before the br tag using Selenium WebDriver

I am trying to retrieve the text between span and br tags. In the HTML snippet below, I am aiming to extract the Orange text:

<td role="grid cell">
<span class="ui-column-title">Fruits</span>
<span id="all fruits">
"Orange"

<br>
23

</span>
</td>

Answer №1

To come up with a simple solution, you can split the text by the new line character in Python:

all_items = driver.find_element_by_css_selector("[id='all items']").text
first_item = all_items.split("\n")[0].replace('"','').strip()

If you want to extract words using regular expressions:

import re

all_items = driver.find_element_by_css_selector("[id='all items']").text
item_name = re.search("\w+", all_items).group()

If you require separating numbers and item names, you can achieve that with regular expressions. The following code will give you two lists, one containing all item names and the other containing numbers (in Python):

import re

all_items = driver.find_element_by_css_selector("[id='all items']").text
item_names = re.findall("[a-zA-Z]+", all_items)
item_numbers = re.findall("[0-9]+", all_items)

Answer №2

Using xpath or plain javascript, you can easily retrieve the desired information:

var fruit = driver.execute_script("""
  return document.querySelector('[id="all fruits"]').firstChild.textContent
""")

Answer №3

To retrieve the text Orange as a text node, you can utilize WebDriverWait to ensure that the element is clickable. Here are two solutions you can use:

  • For Java:

    System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].firstChild.textContent;', new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("//td[@role='grid cell']//span[@id='all fruits']")))).toString());
    
  • For Python:

    print(driver.execute_script('return arguments[0].firstChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[@role='grid cell']//span[@id='all fruits']")))).strip())
    
  • Note (for Python): These imports need to be added :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

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

Add a JavaScript library to the header directly from the body of a webpage, ensuring it is exclusive to a single

I am using the Google Charts JS library on a single page within my project, with external and global headers and footers. The head tags are located in a head.php file, where all required JS libraries are included. The structure of my pages is as follows: ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

What is the maximum level of referencing allowed in v-if conditions?

I'm encountering an issue with some markup I have: <div class="form-group" v-if="model.owner.enabled"> The model object in the scope is structured like this: { ... owner: { enabled: true ... } ... } However, Vue is th ...

Image uploading in Angular is not compatible with Internet Explorer, however, it functions correctly in Google Chrome

As of now, my implementation has been successful in all browsers except for Internet Explorer 11. Despite being able to successfully upload .jpeg, .jpg, and .png images in Google Chrome, I am facing issues when trying to upload them in IE 11. The code wo ...

Receiving data through a POST request in Node

I am currently working on a project where I need to send an email via a POST request to my node/express server. However, I am facing difficulties in passing the email details through the request and accessing them on the node side. Here is what I have tri ...

What is the method to send multiple keys to the web driver using RSelenium, such as pressing ALT+S

Is it possible to send two keys simultaneously, like ALT+S, to the sendKeysToActiveElement( function of the R Selenium webdriver? I've noticed that there are implementations in Java and C, but is there a way to achieve it with R? ...

extracting console log data from a Chrome browser with the help of Python and Selenium

Simply put, I am a beginner when it comes to utilizing selenium with Python. In my endeavor to run a command on a website's console using a Python script, followed by retrieving the output for further use in my script. from selenium import webdriver f ...

What is causing the data added to an array to vanish after the forEach loop within the useEffect hooks?

Below is the code snippet: const Tabs = ({data, scrollX}) => { const [measures, setMeasures] = useState([]); const containerRef = useRef({}); let measureMentArray = []; useEffect(() => { data && data.forEach(item => { ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...

Display information from a mysql database table within a selection menu

Currently, I am working on a dropdown menu that should display data from a MySQL table. However, I am facing an issue which is outlined below: In my PHP script, I have approached it in the following manner: <label class="col-form-label" for="formGrou ...

Updating the route when submitting input value using React-Router

I designed a top bar menu that includes a navbar component along with a form component featuring a text input. This form is responsible for changing the state of the app component, which serves as the parent to the navbar. The navbar, located outside the r ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

Blur Event Triggered in Primefaces Editor

My current setup involves using JSF Mojarra 2.2.8 with PrimeFaces 5.1, where I utilize a PrimeFaces editor for text input. I am looking to automatically upload the entered text via ajax. However, the editor only supports an onchange event. I'm seekin ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

Creating a simulation of a JavaScript callback within a C# host program

Currently, I am in the process of developing a c# application with an embedded web browser control. In this project, I'm facing a challenge where I need to call a C# method from JavaScript and pass a JavaScript callback using the dynamic technique exp ...

a guide on integrating dynamic text input in AngularJS with SVG circles created in D3.js for effective filtering

I am working with a d3js bubble chart that contains multiple circles, each identified by an id corresponding to a city name. var cities = ["Toronto", "London", "Paris"]; In addition, there is a standard input box in the HTML code. <input id="searchBo ...

Failure to return an error in the mongoose find function

While attempting to create some statics with Mongoose, I am facing an issue where I cannot access the error argument when using find() or findOne(). Below is my static method: User.statics.authenticate = function(login, password, cb){ return this.mode ...

What is the best way to apply a Javascript function to multiple tags that share a common id?

I am experimenting with javascript to create a mouseover effect that changes the text color of specific tags in an HTML document. Here is an example: function adjustColor() { var anchorTags = document.querySelectorAll("#a1"); anchorTags.forEach(func ...