Bilal Ahmed
Bilal Ahmed

Reputation: 23

How to handle hyphen (-) in html tagname in selenium python?

I'm getting the error:

no such element: Unable to locate element: {"method":"css selector","selector":"[id="mat-input-3"]"}

I tried the following commands but failed:

email_field = driver.find_element(By.ID, "mat-input-3").send_keys("Admin")
email_field = driver.find_element(By.XPATH, "//*[@id='mat-input-0']").send_keys("Admin")

Code:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service_obj = Service("E:\Bilal Heuristify Office work\Python Automation\Tools\Chrome webdriver\chromedriver.exe")

driver = webdriver.Chrome(service = service_obj)

driver.maximize_window()

driver.get("https://charms-qa.cognitivehealthintl.com/Authorize/")

# email_field = driver.find_element(By.ID, "mat-input-3").send_keys("Admin")
email_field = driver.find_element(By.XPATH, "//*[@id='mat-input-0']").send_keys("Admin")

Upvotes: 2

Views: 832

Answers (2)

ketanvj
ketanvj

Reputation: 511

@Bilal Ahmed, seems your locator is fine. It is just that you need to wait for the element to appear before taking action. So if you can replace the find_element part with the following two lines, it should work.

username = WebDriverWait(driver, 10)\
       .until(expected_conditions.visibility_of_element_located((By.XPATH, "//*[@id='mat-input-0']")))
username.send_keys("Admin").

Also please add the following two imports for it to work.

from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

Upvotes: 0

Conal Tuohy
Conal Tuohy

Reputation: 3215

Your XPath is fine.

The problem is that the body of the web page, including the element you're searching for, is generated by JavaScript. Your Selenium code needs to wait until the element is ready.

See https://selenium-python.readthedocs.io/waits.html

Upvotes: 1

Related Questions