为什么 chrome 关闭? selenium

z2acfund  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(152)
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")

在我

driver.quit()

在代码末尾删除它并不能解决问题

vsmadaxz

vsmadaxz1#

使用time.sleep()或selenium.webdriver.support.ui中的WebDriverWait等待页面完全加载。

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")
pod7payv

pod7payv2#

工作代码:

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()

相关问题