Kirill Zhukov Kirill Zhukov - 1 month ago 5x
Python Question

Python Selenium WebDriver. How to check/verify that drop-down menu with suggested results is displayed?

I wanna make sure that this drop-down menu with suggested results is displayed when I enter something into search field.

enter image description here

Here is my script (not for Google search) which doesn't work:

suggestions = driver.find_element_by_xpath('/html/body/div[6]')
print suggestions.get_attribute('display') # >>>None
if suggestions == "block":
print "Suggestions are displayed!"
print "Suggestions aren't displayed!"

How I understand I have to check that attribute "display" is is "block". If it's "none" it means that drop-down menu isn't displayed.

HTML code of menu with suggested results:

<div style="display: block; position: absolute; width: 237px; top: 270px; left: 186px;" class="ac_results">
<ul style="max-height: 180px; overflow: auto;">
<li class="ac_even ac_over">Elen<strong>a</strong> J<strong>a</strong>mes De<strong>a</strong>n</li>
<li class="ac_odd">Ellie portnov T<strong>a</strong>r<strong>a</strong></li>
<li class="ac_even">Elen<strong>a</strong> Q<strong>A</strong></li>
<li class="ac_odd">Jessy J<strong>a</strong>mes</li>
<li class="ac_even">J<strong>a</strong>mes HotStuff De<strong>a</strong>n</li>
<li class="ac_odd">j<strong>a</strong>mess b<strong>a</strong>g de<strong>a</strong>n</li>
<li class="ac_even">J<strong>a</strong>mes Hotstuff De<strong>a</strong>n</li>
<li class="ac_odd">j<strong>a</strong>mes cool De<strong>a</strong>n</li>
<li class="ac_even">J<strong>a</strong>smin1 Gurusw<strong>a</strong>mi1</li>
<li class="ac_odd">j<strong>a</strong>mes hotguy de<strong>a</strong>n</li>

My code:

suggestions = driver.find_element_by_xpath('/html/body/div[6]')
if suggestions.is_displayed():
print "Suggestions are displayed!"
print "Suggestions aren't displayed!"

  1. Attribute is called style
  2. You can use is_displayed() WebElement's method. It returns True, if element is displayed
  3. You can use expected conditions. Here's an example.
  4. Your code is simply wrong.

    suggestions = driver.find_element_by_xpath('/html/body/div[6]')
    style = suggestions.get_attribute('style')
    if 'block' in style:
        print "Suggestions are displayed!"
        print "Suggestions aren't displayed!"

    This can help, but better use number 3 ;)

UPDATE: As it takes some time to render the needed element, it is a good practice to use waits. Info's here

UPDATE2: You can use this code:

from import By
from import expected_conditions as EC
from import WebDriverWait

WebDriverWait(driver, 5).until(
    EC.visibility_of_element_located((By.XPATH, '/html/body/div[6]')),
    "Element was not displayed after 5 seconds")

If element's visibility is not critical you can use try-except block