Home > OS >  Selenium, how to check if an element exist by its ID
Selenium, how to check if an element exist by its ID

Time:10-05

A web page could contains element by id 'house-info' or 'marketing-remarks-scroll', but not both. I need a solution to verify which element exist. However the following code did not run as I expected. Please advisor what is the right solution.            

> if driver.find_element_by_id('house-info'):
>      marketing_info=driver.find_element_by_id('house-info').text
>  if driver.find_element_by_id('marketing-remarks-scroll'):
>      marketing_info =driver.find_element_by_id('marketing-remarks-scroll').text

CodePudding user response:

Selenium removed find_element_by_id() in 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES

Selenium 4.3.0
* Deprecated find_element_by_* and find_elements_by_* are now removed (#10712)
* Deprecated Opera support has been removed (#10630)
* Fully upgraded from python 2x to 3.7 syntax and features (#10647)
* Added a devtools version fallback mechanism to look for an older version when mismatch occurs (#10749)
* Better support for co-operative multi inheritance by utilising super() throughout
* Improved type hints throughout

You now need to use:

driver.find_element("id", ID)

In your example, those calls would look like this:

driver.find_element('id', 'house-info')

driver.find_element('id', 'marketing-remarks-scroll')

For improved reliability, you should consider using WebDriverWait in combination with element_to_be_clickable.

Another issue in your code is that find_element() raises an Exception if the element isn't found. (You used it in an if statement, but it doesn't return True or False.)

Try adding a method like this to use with your if statements:

def is_element_visible(selector, by="css selector"):
    try:
        element = driver.find_element(by, selector)
        if element.is_displayed():
            return True
    except Exception:
        pass
    return False
  • Related