Home > Mobile >  Why does this Selenium code does not work using Python while trying to target login
Why does this Selenium code does not work using Python while trying to target login

Time:03-17

I am trying to target this bit of code to click a login button

<button  type="submit">Login</button>

This is my python code

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://uplearn.co.uk/login")

element = WebDriverWait(driver, 5).until(EC.presence_of_element_located(By.LINK_TEXT,"Login"))
element.click()

And the error I get is:

DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(PATH)

  element = WebDriverWait(driver, 5).until(EC.presence_of_element_located(By.LINK_TEXT,"login"))
TypeError: presence_of_element_located() takes 1 positional argument but 2 were given

Any solutions?

CodePudding user response:

You are missing a pair of parenthesis.
Instead of

element = WebDriverWait(driver, 5).until(EC.presence_of_element_located(By.LINK_TEXT,"Login"))

It should be

element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.LINK_TEXT,"Login")))

Also, I'd suggest using visibility_of_element_located instead of presence_of_element_located and CSS_SELECTOR or XPATH instead of LINK_TEXT, as following:

element = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"button[type='submit']")))

CodePudding user response:

There are two issues in your code block as follows:

  • executable_path has been deprecated and using Selenium v4.x you have to pass a Service object instead.
  • Expected Conditions like presence_of_element_located() needs to be constructed as tuples.
  • Ideally, to click on a clickable element you need to induce WebDriverWait for the element_to_be_clickable().
  • Finally, Login is not the innerText of any <a> tag, but of a <button> tag, hence LINK_TEXT won't work and you can use either of the following locator strategies:

Your effective code block will be:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

s = Service('C:\\Program Files (x86)\\chromedriver.exe')
driver = webdriver.Chrome(service=s)
driver.get('https://uplearn.co.uk/login')
# using CSS_SELECTOR
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[class*='Login_SubmitButton']"))).click()
# using XPATH
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Login']"))).click()
  • Related