Home > database >  I am unable to click on a text field using id in selenium python
I am unable to click on a text field using id in selenium python

Time:02-27

Here is the image of text field I want to click

This is the inspect field :

<input _ngcontent-oqh-c45="" formcontrolname="target" matinput="" placeholder="https://"  id="mat-input-0" data-placeholder="https://" aria-invalid="false" aria-required="false"> 

This is the code snippet I am using :

enter_url = driver.find_element(By.ID, 'mat-input-0')
enter_url.click()

This is the error I am getting :

Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="mat-input-0"]"}
  (Session info: chrome=98.0.4758.102)

CodePudding user response:

This could be because of three reasons

  1. This is mat-input-0, especially the 0 part is dynamically generated.
  2. The element is not rendered properly.
  3. This field is in iframe or shadow-root.

Check for the below XPath:

//input[@formcontrolname = 'target' and @placeholder='https://' and starts-with(@id,'mat-input') and @aria-invalid='false']

if it's unique or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  1. If it is unique, then we can use explicit wait:

Code:

enter_url = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@formcontrolname = 'target' and @placeholder='https://' and starts-with(@id,'mat-input') and @aria-invalid='false']")))
enter_url.click()

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  1. If the XPath is not unique then we would need more HTML to locate the right element with uniqueness.
  • Related