How to loop python code Selenium?

Asked

Viewed 201 times

0

I need to make the comments (["COMENTARIO1","COMENTARIO2","COMENTARIO3"]) if you repeat N times in a random fill, the way I did, no matter how much I put 30 in the range, they are printed 3 times only.

def comente_foto(self):
    for k in range(30):
        driver = self.driver
        driver.get("https://www.instagram.com/p/B_0ggQsjMJ-/")
        time.sleep(3)
        driver.execute_script("window.scrollTo(0, 90)")
        time.sleep(random.randint(1,3))
        comentarios = ["COMENTARIO1","COMENTARIO2","COMENTARIO3"]
        driver.find_element_by_class_name('Ypffh').click()
        campo_comentario = driver.find_element_by_class_name('Ypffh').clear()
        campo_comentario = driver.find_element_by_class_name('Ypffh').send_keys(comentarios[k])
        time.sleep(random.randint(1,2))
        driver.find_element_by_xpath("//button[contains(text(),'Publicar')]").click()
        time.sleep(random.randint(5,6))

1 answer

0

You have created a list called "comments" with three elements:

comentarios = ["COMENTARIO1","COMENTARIO2","COMENTARIO3"]

In your noose for k varies from 0 to 29, then in the line below:

campo_comentario = driver.find_element_by_class_name('Ypffh').send_keys(comentarios[k])

When k=0 => Writes "COMENTARIO1"

driver.find_element_by_class_name('Ypffh').send_keys(comentarios[0])

When k=1 => Type "COMENTARIO2"

campo_comentario = driver.find_element_by_class_name('Ypffh').send_keys(comentarios[1])  

When k=2 => Type "COMENTARIO3"

 campo_comentario = driver.find_element_by_class_name('Ypffh').send_keys(comentarios[2]) # Escreve COMENTARIO3

When k=3 to 29:=> writes nothing

campo_comentario = driver.find_element_by_class_name('Ypffh').send_keys(comentarios[3])

There is no comment element[3] until comment[29] in your list, Python should give error "list index out of range" but probably Selenium just ignores not writing anything.

To fix the code insert one more FOR loop, follow code:

def comente_foto(self):
    for k in range(30):
        for j range(3): 
            driver = self.driver
            driver.get("https://www.instagram.com/p/B_0ggQsjMJ-/")
            time.sleep(3)
            driver.execute_script("window.scrollTo(0, 90)")
            time.sleep(random.randint(1,3))
            comentarios = ["COMENTARIO1","COMENTARIO2","COMENTARIO3"]
            driver.find_element_by_class_name('Ypffh').click()
            campo_comentario = driver.find_element_by_class_name('Ypffh').clear()
            campo_comentario = driver.find_element_by_class_name('Ypffh').send_keys(comentarios[j])
            time.sleep(random.randint(1,2))
            driver.find_element_by_xpath("//button[contains(text(),'Publicar')]").click()
            time.sleep(random.randint(5,6))

Browser other questions tagged

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