Python Selenium WebDriver。如何检查/验证带有建议结果的下拉菜单?

时间:2014-01-30 17:47:26

标签: python selenium automation selenium-webdriver

我想确保当我在搜索字段中输入内容时,会显示包含建议结果的下拉菜单。

enter image description here

以下是我的脚本(不适用于Google搜索),但不起作用:

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

我如何理解我必须检查属性“display”是否为“block”。如果它是“无”,则表示不显示下拉菜单。

带有建议结果的菜单的HTML代码:

<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>
    </ul>
</div>

我的代码:

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

1 个答案:

答案 0 :(得分:1)

  1. 属性称为style
  2. 您可以使用is_displayed() WebElement的方法。如果显示元素,则返回True
  3. 您可以使用预期条件。 Here's一个例子。
  4. 您的代码完全错误。

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

    这可以提供帮助,但最好使用数字3;)

  5. UPDATE:由于渲染所需元素需要一些时间,因此最好使用等待。信息here

    UPDATE2:您可以使用以下代码:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait
    
    WebDriverWait(driver, 5).until(
        EC.visibility_of_element_located((By.XPATH, '/html/body/div[6]')),
        "Element was not displayed after 5 seconds")
    

    如果元素的可见性不重要,您可以使用try-except块