首页 > 解决方案 > Python Selenium Web 自动化如何单击登录按钮

问题描述

我正在尝试为我的组织自动下载特定文件。在这样做的过程中,我遇到了 Selenium 的浏览器自动化。我已经到了可以注入用户凭据的地步,但现在我需要通过单击登录按钮登录到该页面。

这是父 URL,我在其中注入了我的凭据 https://www.accuplacer.org

然后我需要点击登录按钮。这是该元素的检查输出:

<button type="submit" class="btn btn-lg btn-primary pull-left " ng-disabled="loginDisable &amp;&amp; isFullyLoaded">
                                    <!-- ngIf: loginSpin && !traceIE -->
                                    <!-- ngIf: loginSpin && traceIE -->
                                    Login
                                 </button>

这是我到目前为止的代码,我知道它是基本的,我正在努力清理它并将某些东西定义为函数。

import selenium
import os
import unittest
import requests
import time
from selenium import webdriver

#URL Variables
login_url = 'https://www.accuplacer.org/'
redirect_url = 'https://www.accuplacer.org/api/home.html#/'
reports_scheduler_url = 'https://www.accuplacer.org/api/home.html#/reportScheduler'
custom_reports_url = 'https://www.accuplacer.org/api/home.html#/customReports'

#WebDriver Path
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\chromedriver.exe")

browser.get("https://www.accuplacer.org")

username = browser.find_element_by_id("login")
password = browser.find_element_by_id("password")
#submit = browser.find_element_by_id("Login")
username.send_keys("uname")
password.send_keys("test")

#browser.send_keys(Keys.ENTER)
#browser.send_keys(Keys.RETURN)

#submit.click()
browser.find_element_by_css_selector('btn btn-log btn-primary pull-left').click()

标签: pythonselenium-webdriver

解决方案


你的CSS定位器是错误的。尝试使用以下css具有显式等待的定位器。

element = WebDriverWait(browser, 20).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, ".btn.btn-lg.btn-primary.pull-left")))
element.click();

对于这段代码,您需要在下面导入

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

推荐阅读