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"]
CodePudding user response:
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
- Evaluates the expression (here, it's just the value
index - Calls the
__format__method on the result of the expression, here anint - Since we didn't specify any unusually formats in our f-string,
__format__basically just calls__str__on the value. __str__on an int just returns the decimal string representation of an int (e.g.1.__str__() == '1'
