user3671239
user3671239

Reputation: 31

Python selenium is_displayed method

I want to be able to reach the else statement and not get an exceptions when the element is not displayed.

for example:

 if driver.find_element_by_xpath("/html/body/main/div/article[2]/div[4]/header/div[2]/div/div[3]/a[4]").is_displayed():
            print("yeah found it")
        else:
            print("not found")

Upvotes: 2

Views: 7085

Answers (2)

shuk
shuk

Reputation: 1823

I ran into the same issue and this Q&A block was the game changer. I tweaked the given code by Saifur too, to match my needs, which I believe similar to this question's request:

elementlist = []
found = False
while not found:
    try:
        element_ = browser.find_element_by_xpath("//*[@class='class' and (contains(text(),'Optional-text-contain'))]")
        if element_.is_displayed():
            value = element_.find_element_by_css_selector("*")
            elementlist.append(value.text)
            print("Element: " + value.text)
            found = True
    except NoSuchElementException:
        elementlist.append("N/A")
        print("Element: N/A")
        found = True

This code looks for an alternating element within the page (sometimes exists, sometimes doesn't). If it exists, it gives its' value. If not - it continues normally while appending the list a "NaN" style value, just to match axis for later DFing

Again, Saifur delivered enormous assistance in this issue. Thank you user3691239 for asking this question, and mentioning it worked for you after a lil' tweak.

Upvotes: 1

Saifur
Saifur

Reputation: 16201

You CANNOT call is_displayed() or any other property on an element that does not exist. is_displayed() only would work if the element present in the DOM but hidden or displayed. your program is failing before even reaching the code to check if it is displayed or not. So the possible fix is probably to use some kind of try catch instead

from selenium.common.exceptions import NoSuchElementException

found = False
while not found:
    try:
        link = driver.find_element_by_xpath(linkAddress)
        found = True
    except NoSuchElementException:
        time.sleep(2)

Example code taken from here

Upvotes: 2

Related Questions