from selenium import webdriver
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
options = webdriver.ChromeOptions()
options.binary_location = chrome_path
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.example.com/login.phtml")
form = driver.find_element_by_css_selector("form[name='f']")
username_input = form.find_element_by_name("username")
password_input = form.find_element_by_name("pw")
username_input.send_keys("LOGIN")
password_input.send_keys("PASSWORD")
form.find_element_by_tag_name("button").click()
if driver.current_url == "https://www.example.com/index.phtml":
print("Successful login!")
else:
print("Login failed")
Before i had
driver.quit()
at the end of the code, removing it didn't solve the problem
CodePudding user response:
Use time.sleep() or WebDriverWait from selenium.webdriver.support.ui to wait for page to be fully loaded.
from selenium import webdriver
import time
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
options = webdriver.ChromeOptions()
options.binary_location = chrome_path
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.example.com/login.phtml")
# Wait for the page to fully load before interacting with the page
time.sleep(5)
form = driver.find_element_by_css_selector("form[name='f']")
username_input = form.find_element_by_name("username")
password_input = form.find_element_by_name("pw")
username_input.send_keys("LOGIN")
password_input.send_keys("PASSWORD")
form.find_element_by_tag_name("button").click()
if driver.current_url == "https://www.example.com/index.phtml":
print("Successful login!")
else:
print("Login failed")
CodePudding user response:
Working code:
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.chrome.options import Options
from time import sleep
from selenium.webdriver.common.by import By
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = WebDriver(options=chrome_options)
driver.get("https://www.example.com/login.phtml")
username_input = driver.find_element(By.ID, "id")
password_input = driver.find_element(By.NAME, "pw")
username_input.send_keys("LOGIN")
password_input.send_keys("PASSWORD")
login_button = driver.find_element(By.CSS_SELECTOR, "button.bxpad.ttup")
login_button.click()
sleep(5)
driver.quit()