如何使用 Selenium 定位嵌套 div 中的输入元素

问题描述 投票:0回答:1

我无法找到元素

<input class='search-text'...>
,并且想将文本“hello”放入文本框中。

Trying to locate the input class='search-text'

我的网络驱动程序代码如下

driver.find_element(By.XPATH, "//ul[@class='filter-panel']//li[@class='filter-selection']//filter-selector//div[@class=filter-component]//div//div[@class='search-box-wrapper']/input[@class='search-text']").send_keys("hello")

结果是:

Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//ul[@class='filter-panel']//li[@class='filter-selection']//filter-selector//div[@class=filter-component]//div//div[@class='search-box-wrapper']/input[@class='search-text']"}

我希望将“你好”这个词放在搜索...框中。

搜索...输入框的 HTML 快照:

I'm trying to locate the Search... input box

有人有什么想法吗?谢谢!

python selenium-webdriver xpath css-selectors webdriverwait
1个回答
0
投票
给出 html:

html

所需元素是动态元素。


解决方案

理想情况下,将

字符序列 发送到需要为 element_to_be_clickable() 引发 WebDriverWait 的元素,并且您可以使用以下任一定位器策略

  • 使用

    CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.search-text[aria-label='Enter text for search by keyword']"))).send_keys("yummybagels")
    
    
  • 使用

    XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='search-text' and @aria-label='Enter text for search by keyword']"))).send_keys("yummybagels")
    
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
    
    
© www.soinside.com 2019 - 2024. All rights reserved.