[SOLVED] In Python, How do you iterate through CSS page numbers?

Issue

I’d like to create a loop to iterate through page numbers for aria- label.

browser.find_element_by_css_selector('[aria-label="Page 1"').click()
browser.find_element_by_css_selector('[aria-label="Page 2"').click()
browser.find_element_by_css_selector('[aria-label="Page 3"').click()
browser.find_element_by_css_selector('[aria-label="Page 4"').click()

I tried creating a while loop, but could not get it to work.

x=0
while x<10:
    print(browser.find_element_by_css_selector('[aria-label="Page [x]"'))
    x=x+1

Error message received

    NoSuchElementException                    Traceback (most recent call last)
 NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[aria-label="Page [x]]""}

SO far this code below works:

for index in range(10):
    selector = f'[aria-label="Page {index}"'
    print(selector)

The code above prints

[aria-label="Page 0"]
[aria-label="Page 1"]
[aria-label="Page 2"]
[aria-label="Page 3"]
[aria-label="Page 4"]
[aria-label="Page 5"]
[aria-label="Page 6"]
[aria-label="Page 7"]
[aria-label="Page 8"]
[aria-label="Page 9"]

Solution

The idiomatic Python way to do this would be with a for loop and a format expression:

for index in range(10):
    selector = f'[aria-label="Page {index}"]'
    element = browser.find_element_by_css_selector(selector)
    # Do whatever you want to 'element' here

The range function returns an iterable that yields sequential integers from 0 up to the argument passed excusive. If you want to start a different index, pass that as the first argument range(1, 11).

The format string works by substituting a string representation of the expression included in curly braces. Specifically it

  1. Evaluates the expression (here, it’s just the value index
  2. Calls the __format__ method on the result of the expression, here an int
  3. Since we didn’t specify any unusually formats in our f-string, __format__ basically just calls __str__ on the value.
  4. __str__ on an int just returns the decimal string representation of an int (e.g. 1.__str__() == '1'

Answered By – Nick Bailey

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.