Exploring ways to interact with Span elements using Selenium in Python

Greetings! I am currently attempting to access a specific element called span. My goal is to retrieve this element in a manner that allows me to append it to a list. Each span contains an attribute wordnr="1" or a different number. The objective is to extract each wordnr value and store it in a list.

The source code of the website appears as follows:

<div id="row1" style="top: 1px;"><span wordnr="0" class="highlight">who</span> <span wordnr="1" class="">other</span> ...<span wordnr="45" class="">place</span>

Below is the code that I have written, but unfortunately, it does not seem to be working properly as I am struggling with accessing and locating the desired elements. Kindly note that I am utilizing Repl.it for this task:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

list=[]

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=chrome_options)

driver.get("https://10fastfingers.com/typing-test/english")

words = driver.find_element_by_xpath("//span[@class='wordnr'/span[0]]").text

Answer №1

1 Make sure to click the "Accept cookies" button first in order to access the text.

2 Use item.get_attribute("innerHTML") to retrieve the text. If item.text is not working, you may need to investigate further why that is so intriguing.

3 Utilize Selenium to generate a list with

my_list = driver.find_elements_by_css_selector("#row1>span[wordnr]")
. Avoid creating unnecessary lists as it could result in nested lists in your case.

4 Opt for appropriate explicit waits. Using

visibility_of_all_elements_located
might not be effective if the text is only partially visible.

5 Refrain from using generic identifiers such as list for better code readability. Explore alternative list naming conventions in this engaging discussion on Better Python list Naming Other than "list". My resolution

Customized selenium script goes here ...
(printed 385 words)

Sample end result

385
keep
country
been
their
food
do
...

Displays the complete list consisting of 385 words.

Answer №2

Look out for the "accept all cookies" button, you'll need to give it a click. Here's a snippet of code example:

Sample Code :

driver.maximize_window()
driver.get("https://10fastfingers.com/typing-test/english")
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[id='CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll']"))).click()
sleep(5)
for name in driver.find_elements(By.XPATH, "//span[@wordnr]"):
    print(name.get_attribute('wordnr'))

Dependencies :

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

Answer №3

My approach to solving this would be the following:
First, ensure that the page has fully loaded. Next, retrieve the list of relevant elements and extract the text from each element, adding it to the list.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=chrome_options)
wait = WebDriverWait(driver, 20)

driver.get("https://10fastfingers.com/typing-test/english")
texts_list=[]
# Wait for the first element to be visible
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span[wordnr]")))
# Allow time for the remaining elements to load
time.sleep(1)

elements = driver.find_elements_by_css_selector("span[wordnr]")
for element in elements:
    texts_list.append(element.text)

Answer №4

Let's give this a try:

collection = []
terms = driver.find_elements_by_xpath("//div[@id='row1']/span")
for term in terms:
    collection.append(term.get_attribute("wordnr"))

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

Ways to choose an option from a drop-down menu without the select tag using Selenium

I'm looking to perform automated testing with Selenium using Java but I'm facing an issue when trying to select an item from a dropdown list. The HTML structure does not include a select tag for the drop-down menu items (such as Auth ID and Corre ...

Python script in PowerShell has arguments that include double quotes and whitespace

I am attempting to execute a python script using PowerShell. Within the python script, I am trying to include a command line argument with double quotes and whitespace, but it is not working as expected. It seems like there may be an issue with PowerShell. ...

Issue with passing arguments for entry_points in Setuptools

I have developed a Python script and I am using setuptools Once the installation is complete, I run: $ megazord -i input -d database -v xx-xx -w yy-yy Just like how I would run it as ./like_this However, I encounter the following error: Traceback (mos ...

pyOWM is failing to yield the desired outcome

After obtaining my API key, I attempted to integrate the code snippet below: import pyowm owm = pyowm.OWM('API key') mgr = owm.weather_manager() Forecast = mgr.forecast_at_place('London', '3h').forecast max_temperature=[] min ...

Attempting to utilize Selenium to input data into a text field on a web page

Trying out different versions of WebElement userid = driver.findElement(By.xpath and WebElement email = driver.findElement(By.id("email")); has resulted in syntax errors for me. If you need a visual reference, check out this image of the textbox ...

Exploring the concept of Starred Expression

Currently, I am working on implementing some reinforcement learning algorithms in a basic game. However, instead of dealing with RL issues, the problem seems to be more related to Python syntax. There is an issue with the starred expression that I can&apos ...

Converting strings to floats in Python without relying on specific locales

When trying to convert a string to a float, I encounter various input formats like '1234,5', '1234.5', '1 234,5', or '1,234.5'. The challenge is that I can't adjust the locale decimal pointer or thousands separa ...

Query a string in MongoDB using Python3

I am faced with the challenge of creating a dynamic query in MongoDB without prior knowledge of how many variables I will have. The goal is to eliminate duplicates by using the $or operator. def findRecipes(IngredientsHome): #Query and return all the alte ...

Using a Django model field to automatically populate another field

Hello again, it's been over 48 hours and I'm still struggling to find a solution to this issue. Here is the scenario: I have a model called Engineers, which includes positions like Site Engineer, Site Manager, HVAC Engineer, etc. Now, the requ ...

Tips for reducing the browser window size in Selenium WebDriver 3

Once the browser window has been maximized using driver.manage().window().maximize();, what is the method to minimize it in Selenium WebDriver with Java? ...

Creating a 2-dimensional array of binary digits using Python

Currently experimenting with this Python code snippet: input = [] for i in range(10): n = getBin(i, 4) input.append(n) print input The output is: ['0000', '0001', '0010', '0011', '0100', '0101 ...

MatPlotLib Pcolormesh displaying incorrectly

I've been attempting to replicate the steps outlined in this tutorial: The goal is to create a heat map similar to this example: https://i.stack.imgur.com/qW8Yo.gif However, instead of the desired output, I'm getting this result: https://i.st ...

Verify if the file uploaded in django is a zip file

I'm working on a POST method handler in Django that deals with uploaded files, and I want to ensure that the file is a valid zip file before continuing. My current code snippet looks like this: @login_required(login_url="login/") def upload(request) ...

determining a precise match with Selenium through text-based criteria

Suppose I have a piece of HTML that looks like this: <span class="select2-selection__rendered" id="select2-plotResults-container" role="textbox" aria-readonly="true" title="50">50</span> Now, if I want to locate it using a method similar to ...

Issues with deleting dictionaries from a list using Python

I have encountered a puzzling issue in my code. There are certain pieces of logic where keys/values or dictionaries get removed under specific conditions. However, when these objects are added to a top-level dictionary and converted into a JSON object, the ...

Is there an issue with HTTP Basic Authentication through the URL in Firefox?

Typically, you can access sites requiring HTTP basic authentication using Selenium by including the username and password in the URL like this: selenium.open("http://myusername:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20 ...

The ElementClickInterceptedException error is thrown when the element at the specified point (x, y) is not clickable due to another element overlapping and

Issue Alert: The error encountered is as follows: ElementClickInterceptedException: Message: element click intercepted: Element <a href="report_exec_hc_1.php?report_id=...">SENECA01</a> is not clickable at point (100, 740). Another el ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

The Python interpreter behaves consistently across different platforms, except for a specific issue with json_set in Visual Studio Code

I can't seem to understand what's going on. The code works fine everywhere except in Visual Studio Code. Take a look at this example: import sqlite3 _connection = sqlite3.connect(":memory:") connection.row_factory = sqlite3.Row create_table = ...

Utilize the same web browser across numerous test scenarios in Katalon Studio

I've been on a quest to discover if there's a way to use the same browser for multiple test cases. The website I'm testing requires each login when the browser is opened. Is there a feature that would enable me to maintain the same browser ...