首页 > 解决方案 > Selenium with Python - 如何让它一次填写一个文本框

问题描述

我正在使用 Selenium 和 Python 登录网站,因此它必须将用户名传递给一个文本框,然后将密码传递给另一个文本框。当它填写用户名时,它有时会开始在同一个文本框中输入密码(它通常不会输入完整的密码,只输入其中的一部分)。这就像它试图输入太快,然后在选择密码文本框之前开始输入密码。如何让它按顺序输入文本?

from selenium import webdriver

driver = webdriver.Chrome(executable_path=Config.driver_path)
driver.get(Config.start_url)
driver.find_element_by_xpath('//someXPathToUsername').send_keys(Config.username)
driver.implicitly_wait(Config.driver_wait_time)
driver.find_element_by_xpath('//someXPathToPassword').send_keys(Config.password)
driver.implicitly_wait(Config.driver_wait_time)
driver.find_element_by_xpath('//someXPathToLoginButton').click()

标签: pythonseleniumselenium-webdriverselenium-chromedriver

解决方案


您需要对其进行设置,以便它查找您想要定位的 div 的类或 id 在此处查看有关 Selenium 定位元素的更多信息我认为这是您的问题,它不知道要定位什么,然后它完全做到了错误的。

看看我做的以下代码

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import pprint as pp
import time
from selenium.webdriver.common.keys import Keys


def login(driv):
#insert the website url between the ('')
    driv.get('WebsiteURLHere')
 #select the username div by id
    login_email = driv.find_element_by_id_name('username')
#select the password div by id
    login_password = driv.find_element_by_id_name('password')
#enters the email address in the username field 
    login_email.send_keys('EmailAddressHere') 
#enters the password in the password field  
    login_password.send_keys('passwordhere') 
#finds the sumbit button and a click command to send info
    driv.find_element_by_id('btn__primary').click() 
    time.sleep(3)
    return (driv)

推荐阅读