如何在 div 内定位输入

How to locate the input within div

我在读取 XPath 时遇到问题。需要一些 help/advise 专家。

部分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>
            <!---->

我尝试 select 使用 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]"}

INPUT 元素不是您在定位器中引用的 DIV 的 child,正如 / 运算符所隐含的那样。 / 是 child(向下一层),// 是任何后代(向下一层或多层)。所以你的 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"]

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

#nav-typeahead-wormhole input

所需的 <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