Loop in Selenium (python)

Asked

Viewed 418 times

1

Hello, I need to display a chart in a browser (Chrome) but this chart requests authentication after a while. I learned about the Selenium tool yesterday and decided to use it to perform an auto-login. How could I make Selenium identify that it left the chart and went to the login screen and then login?

import time
from selenium import webdriver

user = "usuario"

pwd = "senha"

driverpath = "/caminho/do/driver/chromedriver.exe"
driver = webdriver.Chrome(driverpath)

driver.get("https://gmail.com")


elem = driver.find_element_by_id("username")
elem.send_keys(user)

elem = driver.find_element_by_id("password")
elem.send_keys(pwd)

driver.find_element_by_class_name("ZLoginButton").click()

time.sleep(5)

driver.close()

1 answer

0

You can make use of the try and the except in form:

import time
from selenium import webdriver

user = "usuario"

pwd = "senha"

driverpath = "/caminho/do/driver/chromedriver.exe"
driver = webdriver.Chrome(driverpath)

driver.get("https://gmail.com")

try:

    driver.find_element_by_id("grafico").click()

except:

    elem = driver.find_element_by_id("username")
    elem.send_keys(user)

    elem = driver.find_element_by_id("password")
    elem.send_keys(pwd)

    driver.find_element_by_class_name("ZLoginButton").click()

    time.sleep(5)

driver.close()

This way, if Selenium does not locate the element inside the Ry, it will run what is inside the except.

Browser other questions tagged

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