What is the best way to increase the index by 1 with each iteration of the loop?

I am trying to figure out how to increment the index by 1 each time a loop runs, but I seem to be struggling with it.

Here is the current piece of code that I have:

categoryindex = categorylist[1]

while True:
    try:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[child::span[text()='{oddsnumber}'] and span[text()='{oddstype}']]"))).click()
    except:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException,)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[text() ='{categoryindex}']"))).click()

I would like the index to start at [1] and continue until the requested element is found. I attempted to use an increment (+) operator, but I'm unsure of how it works with indexes.

Answer №1

One efficient way is to utilize a for loop while incorporating the break statement. This method allows the loop to halt as soon as the desired element is found, and if not found, it will automatically move on to the next index for further checking.

for i in range(1, len(categorylist)):
    categoryindex = categorylist[i]
    try:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[child::span[text()='{oddsnumber}'] and span[text()='{oddstype}']]"))).click()
      
    except:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException,)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[text() ='{categoryindex}']"))).click()

Answer №2

To iterate through a list without using indices, you can utilize the `next()` function along with an iterator created from your iterable. The iterable in this case is represented by a list named `categorylist`. To create an iterator from this list, simply use `iter(categorylist)`.
Once you have the iterator, you can use the `next()` function to retrieve items one by one from the list each time you call it.
For example:

my_list = ['a', 'b', 'c', 'd']
my_list_iterator = iter(my_list)
print(next(my_list_iterator)) #output: 'a'
print(next(my_list_iterator)) #output: 'b'
print(next(my_list_iterator)) #output: 'c'
print(next(my_list_iterator)) #output: 'd'

If you try to call `next()` once you've reached the end of the list, a `StopIteration` exception will be raised.
To handle this error, there are two approaches:

# Approach 1: Provide a default value as the second parameter to next() function
my_list = ['a', 'b', 'c', 'd']
my_list_iterator = iter(my_list)
MY_DEFAULT = 'my_default'
print(next(my_list_iterator, MY_DEFAULT)) #output: 'a'
print(next(my_list_iterator, MY_DEFAULT)) #output: 'b'
print(next(my_list_iterator, MY_DEFAULT)) #output: 'c'
print(next(my_list_iterator, MY_DEFAULT)) #output: 'd'
print(next(my_list_iterator, MY_DEFAULT)) #output: 'my_default'
...
print(next(my_list_iterator, MY_DEFAULT)) #output: 'my_default'

# Approach 2: Use next() a fixed number of times based on list size:
for i in range(len(my_list)):
    print(next(my_list_iterator))
# outputs: prints 'a', 'b', 'c', 'd' each on a new line

How can you implement this in your code?

categorylist_iterator = iter(categorylist)

next(categorylist_iterator) # skip the 0th index to start iteration from index 1
while True:
    categoryindex = next(categorylist_iterator)
    try:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[child::span[text()='{oddsnumber}'] and span[text()='{oddstype}']]"))).click()
    except:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException,)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[text() ='{categoryindex}']"))).click()

However, you need to prevent the `StopIteration` error in your code. If the iteration on `categorylist` reaches its end, the error will occur!

DEFAULT_INDEX = 'A value which not exists in the list categorylist. for example it can be a random token'
categorylist_iterator = iter(categorylist)

next(categorylist_iterator) # skip the 0th index to start iteration from index 1
while True:
    categoryindex = next(categorylist_iterator, DEFAULT_INDEX)
    if categoryindex == DEFAULT_INDEX:
        break
    try:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[child::span[text()='{oddsnumber}'] and span[text()='{oddstype}']]"))).click()
    except:
        ignored_exceptions = (NoSuchElementException, StaleElementReferenceException,)
        WebDriverWait(driver, 20, ignored_exceptions=NoSuchElementException).until(EC.element_to_be_clickable((By.XPATH, f"//div[text() ='{categoryindex}']"))).click()

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

Struggling to access any Https sites while attempting to utilize a proxy with selenium

Having issues accessing an https site using a proxy with selenium. The following is the code I have written: from selenium import webdriver PROXY = "159.203.11.15:80" # IP:PORT or HOST:PORT chrome_options = webdriver.ChromeOptions() chrome_options.add_ ...

Tips for efficiently scraping multiple hrefs within a webtable using Selenium

I am currently faced with the challenge of web scraping a website using Python and Selenium. The information I need is spread across different pages linked in the 'Application number' column. How can I programmatically click on each link, navigat ...

Retrieving a JavaScript variable's value in Selenium with Python

rwdata = driver.find_elements_by_xpath( "/html/body/div[2]/div/div/div/form[2]/div[2]/table/tbody") This table contains the value of variable r as text/javascript type. for r in rwdata: print(r.text) if r.text != "Booked": ...

Is it possible to conduct HTML-based Selenium tests without an internet connection?

As a newcomer to Selenium, I am currently using the Selenium IDE which has led me to create table structures like the one below: <table cellspacing="1" cellpadding="1" border="1" name="SELENIUM-TEST"> <thead> <tr class="title"> ...

Mastering the process of running selenium automation scripts (written in Java) with Safari Technology Preview

Seeking assistance with running automation scripts on Safari. Currently utilizing Selenium Webdriver scripts on Mac OS (High Sierra) and Safari 11.1.2 I've added the WebDriver Extension to the Safari browser and enabled 'Allow Remote Automation ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

Regular Expression - Replace all non-alphanumeric characters and accents with empty strings

Is there a way to remove all special characters except alphanumeric and accents? I attempted the following: text = 'abcdeáéí.@# ' re.sub(r'[^a-zA-Z0-9áéíóúÁÉÍÓÚâêîôÂÊÎÔãõÃÕçÇ: ]', ' ', text) Unfor ...

Gather identification (ID) and row count from SQL query and store in the column labeled value

I am working with a dataframe that has the following structure: ID SQL 0 ID_24 Select * from table1 1 ID_42 Select * from table2 My goal is to create a for loop that loops through these rows and adds the number of ...

What is the process for changing a text file into a dictionary and displaying the contents?

My data is organized into three columns of information: 2 12345 1.12345 1 54321 1.54321 3 12345 1.12345 I want Python to convert the first two columns into keys and the third column into values, but since my file is too large to manuall ...

What is the best method for retrieving text before and after a specific word in Excel or Python?

I have a large block of text with various lines like: ksjd 234first special 34-37xy kjsbn sde 89second special 22-23xh ewio 647red special 55fg dsk uuire another special 98 another special 107r green special 55-59 ewk blue special 31-39jkl My goal is to ...

Scraping data from dropdown menus with Selenium in web development

When attempting Selenium web scraping, I encountered the following issues: Dropdown list did not change as expected Unable to scrape desired results Unsuccessful in resolving the problems Here is a snippet of the code used: ''' from seleni ...

Having trouble populating the current date into a web form using Selenium, by retrieving it from an Excel sheet

I already know how to retrieve the current date, but now I need to set it as the previous day's date. My biggest challenge is figuring out how to input this yesterday's date into a web form using Selenium. The form requires information such as s ...

What are the best techniques for incorporating constraints into optimization problems with docplex using Python?

I'm facing an optimization challenge similar to the knapsack problem and need help in solving it. The details of the problem can be found in this post: knapsack optimization with dynamic variables I want to transition from OPL to Python for this task, ...

Searching for an element using Python's Selenium and JavaScript

on this page I am trying to click on the "Choose file" button but I keep getting the error message: javascript error: argument is not defined var1 = sys.argv[1] path = os.path.abspath(var1) driver.get("https://www.virustotal.com/gui/home/upload& ...

creating a parabolic shape within a section of a cyclical wave using the numpy library

A repetitive signal with slight variations in each cycle occurs approximately every second. Each cycle differs slightly in duration and content within certain parameters. The signal data consists of a thousand x,y coordinates per second, with a small but s ...

Adding text to the end of a web address through a submission form

Here is an example of a form: <form method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Engine"> <input type="submit"> I am looking t ...

The synchronization between Selenium and ChromeDriverManager fails to grab the most recent update of ChromeDriver

I encountered an issue: Error: Type: <class 'selenium.common.exceptions.SessionNotCreatedException'> Message: session not created: This version of ChromeDriver only supports Chrome version 96 Current browser version is 98.0.4758.82 with bin ...

Leveraging the get_account_funds function within the betfair.py library

I have been attempting to utilize the get_account_funds function in the betfair.py package found at https://github.com/jmcarp/betfair.py. The example code provided in the readme file demonstrates the list_event_types function working correctly, indicating ...

Error: Element not found - The specified CSS selector [id="loginUsername"] cannot be located in the document

Struggling to master the art of Web Scraping with Python through Selenium, my current testing grounds are Reddit.com. Unfortunately, I’ve hit a roadblock during script execution which halts at the login page, throwing this error message: (selenium.common ...

the x-axis of the graph object is failing to update

Here is a snippet of the code I'm working with: from plotly.subplots import make_subplots import plotly.graph_objects as go surf=make_subplots( rows=1, cols=2, subplot_titles=( 'Surface growing for {} seconds'.format(sto ...