Extract multiple values from a variable

Asked

Viewed 52 times

-3

I’m picking up information from a site where the number of the div changes, have some way to get tried all the numbers up to a limit or need to type them manually ?

try:
 x = 1
 driver.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/div[{}]/div".format(x)).click()

The x needs to be from 1 to 500 for example.

  • Loop and use a counter

1 answer

0

As indicated in the comments by @Magichat, this is a typical use of a loop

for x in range(500):
    try:
        driver.find_element_by_xpath(f"/html/body/div[3]/div/div[2]/div/div[{x}]/div").click()

the problem of the above code is that you would click on all the elements that had this div number from 1 to 500. A possibly more suitable alternative is:

encontrou = False
x = 0
while not encontrou:
    try:
        driver.find_element_by_xpath(f"/html/body/div[3]/div/div[2]/div/div[{x}]/div").click()
    except:
        # em caso de erro, passe adiante
        pass
    else:
        # caso não haja erro, o else é executado, encerrando o loop 'while'
        encontrou = True
    finally:
        # independente de haver ocorrido erro, incremente a variavel x
        x += 1

this code will end at the first value of x that does not raise an exception.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.