Home > database >  InvalidSelectorException occurs when trying to locate an element with ID--selenium, python
InvalidSelectorException occurs when trying to locate an element with ID--selenium, python

Time:09-05

driver.implicitly_wait(2)
question = driver.find_element('id', '//*[@id=question]')
question.get_attribute('value')

I'm trying to get the value of the element with id='question'.

CodePudding user response:

Your Syntax is wrong, try the below

driver.implicitly_wait(2)
question = driver.find_element(By.ID, 'question')
question.get_attribute('value')

CodePudding user response:

This is an easy fix. You need to import and use By in order to create a valid selector. Also, you've not assigned the value attribute to any variable; I would suggest you try this:

from selenium.webdriver.common.by import By

driver.implicitly_wait(2)
question = driver.find_element(By.ID, 'question')
value = question.get_attribute('value')

CodePudding user response:

You have to specify according to which criteria you want to locate the element.

So for example:

from selenium.webdriver.common.by import By

question = driver.find_element(By.XPATH, '//*[@id=question]')
id = question.get_attribute('id')

or in one line:

id = driver.find_element(By.XPATH, '//*[@id=question]').get_attribute('id')

P.s: I suggest you to always use explicit waits instead of implicit ones.

  • Related