如何使用Selenium和Python为下面的html找到元素

2024-06-02 10:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为下面的html标记找到xpath。但无法定位在硒.as我是初学者,我需要一些帮助和建议。获取错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class='react-autosuggest__input react-autosuggest__input--open']"}
(Session info: chrome=73.0.3683.103)

这是HTML元素。你知道吗

<input type="text" autocomplete="off" aria-autocomplete="list" aria-controls="react-autowhatever-1" class="react-autosuggest__input react-autosuggest__input--open" placeholder="From" value="">

我已经尝试了,并为上面的xpathHTML。但是抛出错误也是如此。你知道吗

//*[@class='react-autosuggest__input react-autosuggest__input--open']   

我希望上面xpath的输出能够在selenium中定位元素,但实际上我得到了一个错误。你知道吗


Tags: 标记定位元素inputhtmlselenium错误autosuggest
2条回答

尝试使用WebDriverWait,只设置较长的等待时间,例如:

element = WebDriverWait(driver, 60).until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, "input[placeholder='From']")))

元素似乎是React元素,因此要定位元素,必须导出WebDriverWait,才能单击元素,并且可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.react-autosuggest__input.react-autosuggest__input open[placeholder='From']")))
    
  • 使用XPATH

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='react-autosuggest__input react-autosuggest__input open' and @placeholder='From']")))
    
  • 注意:必须添加以下导入:

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

相关问题 更多 >