Python Selenium send_keys one by one

Tags: , , , ,



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

I am trying to login to this site automatically using Python-Selenium. However, as you might noticed the password input place is not receiving driver.send_keys.

code:

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')

Answer

1 The site starts blocking automated requests after some amount of them is sent. I’ve added one option on how to avoid bot detection. Look for similar questions on this.

2 You can wait for you alert and check the text inside it.

3 Do not Use time.sleep, use implicit/explicit wait Points 2 and 3 were the main problems in your code.

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.

UPDATE and solution

I found out that you start seing a virtual keyboard after some amount of attempts. So, you can bypass it with Javascript:

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

Instead of

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


Source: stackoverflow