使用selenium在具有虚拟键盘的网站上输入密码

2024-10-03 11:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用selenium登录一个网站。但是当它到达密码页面时,站点要求通过虚拟键盘输入,而send_keys命令不起作用。你知道吗

代码:

import time
from selenium import webdriver as wd
from selenium.webdriver.common.keys import Keys

# Página 1
chrome = wd.Chrome(executable_path='R:\\USUARIOS\\YVieira\\chromedriver.exe')
chrome.get('https://extranet.btgpactual.com')
user=chrome.find_element_by_id('txtLogin')
user.send_keys('yan.vieira')
user.send_keys(Keys.ENTER)
time.sleep(3)
#Página 2

senha=chrome.find_element_by_id('txtSenha')
senha.send_keys("pssw")

HTML代码:

<input type="password" id="txtSenha" name="txtSenha" maxlength="100">

enter image description here


Tags: 代码fromimportsendidtimeseleniumkeys
2条回答

您可以定义一个函数来遍历密码的每个字母,比如(因为虚拟键盘-根据您的屏幕截图-是一种div元素,每个元素都有key属性,该属性的值与键盘元素的键值相对应)

passwd = "my pass"
for key in passwd:
  chrome.find_element_by_xpath('//div[@key="' + key + '"]').click()

只需单击页面上相应的div。你知道吗

附:这个简单的例子被用来处理不需要shift键值的简单密码

您可以尝试使用JavaScript设置值:

password = "pssw"
senha=chrome.find_element_by_id('txtSenha')
chrome.execute_script(f"arguments[0].value='{password}'", senha)
chrome.find_element_by_id("btnValidate").click()

相关问题 更多 >