如何在div中定位输入

时间:2018-12-26 23:03:13

标签: python-2.7 selenium-webdriver xpath css-selectors webdriverwait

我在阅读XPath时遇到问题。需要专家的帮助/建议。

部分HTML代码:

<div id="nav-typeahead-wormhole">
    <div class="nav-search-typeahead">
        <artdeco-typeahead-deprecated id="nav-search-artdeco-typeahead" class="search-typeahead-v2 ember-view">
            <artdeco-typeahead-deprecated-input id="ember35" class="ember-view">
                <!---->
                <input role="combobox" autocomplete="off" spellcheck="false" aria-autocomplete="list" aria-expanded="false" placeholder="Recherche" type="text">
            </artdeco-typeahead-deprecated-input>
            <!---->

我尝试使用Xpath在div id="nav-typeahead-wormhole"中选择输入

我的代码如下:

search = browser.find_element_by_xpath("//div[@id='nav-typeahead-wormhole']/input[1]")

我收到此错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@id='nav-typeahead-wormhole']/input[1]"}

3 个答案:

答案 0 :(得分:1)

INPUT元素不是您在定位器中引用的DIV的子元素,正如/运算符所暗示的那样。 /是子级(向下一级),//是子孙(向下一级或多个一级)。因此,您的XPath应该是:

//div[@id='nav-typeahead-wormhole']//input[1]

其他替代方法是:

//div[@id='nav-typeahead-wormhole']/div//input

//artdeco-typeahead-deprecated[@id='nav-search-artdeco-typeahead']/artdeco-typeahead-deprecated-input/input

//artdeco-typeahead-deprecated/artdeco-typeahead-deprecated-input/input

//div[@id="nav-typeahead-wormhole"]//input[@placeholder="Recherche"]

答案 1 :(得分:0)

Xpath很慢。尝试使用CSS选择器:

#nav-typeahead-wormhole input

答案 2 :(得分:0)

所需的<input>元素是基于Ember.js的元素,因此要标识该元素,需要诱导 WebDriverWait 使元素可点击,您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    search = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#nav-typeahead-wormhole input[placeholder='Recherche']")))
    
  • 使用XPATH

    search = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='nav-typeahead-wormhole']//input[@placeholder='Recherche']")))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC