【问题标题】:Selenium finds wrong element, an element that doesn't even existSelenium 找到了错误的元素,一个甚至不存在的元素
【发布时间】:2020-08-01 23:25:50
【问题描述】:

我正在检查 Firefox 中的 youtube 搜索栏并得到:

<input id="search" autocapitalize="none" autocomplete="off" autocorrect="off" name="search_query" tabindex="0" type="text" spellcheck="false" placeholder="Search" aria-label="Search" aria-haspopup="false" role="combobox" aria-autocomplete="list" dir="ltr" style="outline: currentcolor none medium;" class="ytd-searchbox">

我有以下代码:

driver = webdriver.Firefox()
driver.get("http://www.youtube.com")
elem = driver.find_element_by_id("search")
elem.send_keys("asdfasdf")
elem.send_keys(Keys.RETURN)

并得到以下错误(使用 firefox gecko webdriver):

    raise exception_class(message, screen, stacktrace)
    selenium.common.exceptions.ElementNotInteractableException: Message: Element <g id="search"> is not reachable by keyboard

为什么?当我检查源代码时,没有 id="search" 的 g 元素,这是怎么回事?

【问题讨论】:

    标签: python selenium web web-scraping


    【解决方案1】:

    ElementNotInteractableException在找到元素时发生,但您无法与之交互。

    原因有很多:

    • 元素不可见/不显示
    • 元素不在屏幕上
    • 元素在另一个元素的后面或隐藏

    要解决您的问题,您需要使用 actionchain,参考以下解决方案:

    试试下面的代码:

    url = 'http://www.youtube.com'
    driver.get(url)
    driver.maximize_window()
    wait = WebDriverWait(driver, 20)
    
    element = wait.until(EC.presence_of_element_located((By.XPATH, "//form[@id='search-form']//div[@id='container']//div[@id='search-input']//input")))
    
    actionChains = ActionChains(driver)
    actionChains.move_to_element(element).click().perform()
    actionChains.move_to_element(element).send_keys("Bollywood",Keys.RETURN).perform()
    

    注意:请在您的解决方案中添加以下导入

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

    输出:

    【讨论】:

    • 谢谢,但 EC 和 By 是什么?你知道为什么我的代码不起作用吗?努力学习。
    • 啊,对不起。是的,这行得通。你知道为什么我的代码不起作用吗?我尝试在我的代码中等待 10 秒,但没有成功
    • 也添加了答案,你能不能对accept回答并从你的最后点击upvote按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多