Selenium:如何在按下登录按钮之前等待浏览器加载已保存的用户名/密码

问题描述 投票:0回答:1

在Python中: 当我使用特定的配置文件(因此已经保存了用户名和密码)时,等待浏览器自动输入数据然后再继续的最佳方法是什么?

python selenium-webdriver selenium-chromedriver
1个回答
0
投票

当填写表单中的输入时,它会获得一个名为

"value"
的属性。我们可以用它来检测用户名和密码是否已填写。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import TimeoutException

def getConfiguredDriver()->WebDriver:
    """ returns driver with correct options"""
    pass

driver:WebDriver = getConfiguredDriver()


def attempt_login(driver:WebDriver, url:str, delay:float)->bool:
    """
    :param driver: the browser that is being used
                   NOTE: must be configured to a specific profile.
    :param url: - the url of the page you want the browser to auto-fill
    :param delay: the maximum amount of time you want the driver to wait in seconds
    
    :return: True if successful in logging in, else False
    """

    driver.get(url)

    def predicate(driver:WebDriver):
        IDS:tuple[str,...] = ("username", "password")
        condition:bool = all(driver.find_element(By.ID,id).get_attribute("value")!=None for id in IDS)
        # condition is True if username and password are filled in else False.
        return driver.find_elem("id","login button") if condition else False

    try:
        login_button:WebElement = WebDriverWait(driver,3).until(predicate)
        login_button.click()
        return True
    except TimeoutException:
        return False

if (attempt_login(driver,url,3)):
    print("success")
else:
    print("failure")

注意,“用户名”、“密码”和“登录按钮”只是填充 ID,请参阅您尝试登录的页面的 html 以获取每个元素的 ID。

© www.soinside.com 2019 - 2024. All rights reserved.