Python Seleniu逐个发送_键

2024-09-30 06:34:38 发布

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

https://www.bccard.com/app/merchant/Login.do

我正在尝试使用Python Selenium自动登录此站点。但是,正如您可能注意到的,密码输入位置没有接收driver.send_keys

代码:

from selenium import webdriver
import time

driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')

driver.get('https://www.bccard.com/app/merchant/Login.do')
time.sleep(2)
alert = driver.switch_to_alert()
alert.dismiss()

driver.find_element_by_xpath('//*[@id="userid"]').send_keys('id')
driver.find_element_by_xpath('//*[@id="passwd"]').send_keys('pw')

Tags: httpsimportcomsendidappwwwdriver
3条回答

您的代码对我来说很好,只需切换:

alert = driver.switch_to_alert()

为此:

alert = driver.switch_to.alert

至少对我来说,switch_to_alert()在Pycharm中已被弃用并出现错误

除了用户ID和密码之外,请填写好

1在发送了一定数量的自动请求后,站点开始阻止这些请求。我添加了一个关于如何避免机器人检测的选项。在这方面寻找类似的问题

2您可以等待警报并检查其中的文本

3不要使用时间。睡眠,使用隐式/显式等待 第2点和第3点是代码中的主要问题

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC

options = Options()
#  Try adding user agent to avoid bot detection
# options.add_argument('user-agent=')
driver = webdriver.Chrome(chrome_options=options, executable_path='/snap/bin/chromium.chromedriver')
driver.get('https://www.bccard.com/app/merchant/Login.do')
driver.implicitly_wait(10)

wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())
alert = driver.switch_to.alert
assert "INISAFE CrossWebEX" in alert.text
alert.dismiss()

driver.find_element_by_css_selector('li>#userid').send_keys('id')
driver.find_element_by_css_selector('span>#passwd').send_keys('pw')
time.sleep(7)  # just to make sure that the values was entered.

更新和解决方案

我发现,经过多次尝试后,您开始使用虚拟键盘。因此,您可以使用Javascript绕过它:

field = driver.find_element_by_css_selector('span>#passwd')
driver.execute_script(f"arguments[0].value='pw'", field)

而不是

driver.find_element_by_css_selector('span>#passwd').send_keys('pw')

您可以引入显式等待以获得更高的稳定性。以下代码适用于我:

driver = webdriver.Chrome("C:\\Users\\cruisepandey\\Desktop\\Selenium+Python\\chromedriver.exe")
driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://www.bccard.com/app/merchant/Login.do")
alert = driver.switch_to.alert
alert.dismiss()
wait.until(EC.element_to_be_clickable((By.ID, 'userid'))).send_keys('Robin shim')
wait.until(EC.element_to_be_clickable((By.ID, 'passwd'))).send_keys('Robin shim password')
print("login successfully")

Check out the output

相关问题 更多 >

    热门问题