16

I'm trying to locate element by

element=driver.find_element_by_partial_link_text("text")

in Python selenium and the element does not always exist. Is there a quick line to check if it exists and get NULL or FALSE in place of the error message when it doesn't exist?

Oleksandr Makarenko
  • 779
  • 1
  • 6
  • 18
Nelly Kong
  • 279
  • 1
  • 2
  • 18
  • What exactly do you mean by `quick statement to check`? Selenium doesn't supports `statement`. You have to write a line/block of code. – undetected Selenium Aug 15 '17 at 15:17
  • `driver.find_element_by_partial_link_text("text")` is quick enough way to check if element exists... Can you be more explicit about what you want your code to do? – Andersson Aug 15 '17 at 15:37
  • It gives error message when the element does not exist. Is it possible get a NULL or FALSE when it does not exist? – Nelly Kong Aug 15 '17 at 15:40

2 Answers2

38

You can implement try/except block as below to check whether element present or not:

from selenium.common.exceptions import NoSuchElementException

try:
    element=driver.find_element_by_partial_link_text("text")
except NoSuchElementException:
    print("No element found")

or check the same with one of find_elements_...() methods. It should return you empty list or list of elements matched by passed selector, but no exception in case no elements found:

elements=driver.find_elements_by_partial_link_text("text")
if not elements:
    print("No element found")  
else:
    element = elements[0]  
Andersson
  • 51,635
  • 17
  • 77
  • 129
6

Sometimes the element does not appear at once, for this case we need to use explicit wait:

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 5)

def is_element_exist(text):
    try:
        wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, text)))
    except TimeoutException:
        return False

Solution without try/ except:

def is_element_exist(text):
    elements = wait.until(EC.presence_of_all_elements_located((By.PARTIAL_LINK_TEXT, text)))
    return None if elements else False

How explicit wait works you can read here.

Imports:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Oleksandr Makarenko
  • 779
  • 1
  • 6
  • 18