使用 Selenium 时出现 NoSuchElementException

NoSuchElementException when using Selenium

打开网页后,webdriver找不到“name”元素?

Traceback (most recent call last):
  File "main.py", line 19, in <module>
    driver.find_element(By.NAME,"nickname").send_keys(username+Keys.ENTER)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="nickname"]"}
  (Session info: chrome=)
Stacktrace:
#0 0x5574d3a05919 <unknown>

这是我使用的 HTML 来源:

<input name="nickname" type="text" placeholder="Nickname" maxlength="15" id="nickname" data-functional-selector="username-input" class="sc-gTgzIj eFnEAY" autocomplete="off" value="" aria-expanded="false">

请检查 dev tools (Google chrome) 我们是否在 HTML DOM 中有 unique 条目。

检查步骤:

Press F12 in Chrome -> 转到 element 部分 -> 执行 CTRL + F -> 然后粘贴 xpath 并查看是否需要 element正在 突出显示 1/1 匹配节点。

如果这是唯一的 //input[@id='nickname' and @name='nickname'] 那么您还需要检查以下条件。

  1. 检查它是否在任何 iframe/frame/frameset 中。
  2. 检查它是否在任何 shadow-root 中。
  3. 确保在与元素交互之前正确呈现该元素。放一些 hardcoded delayExplicit wait 然后再试一次。
  4. 如果您已重定向到 new tab/ or new windows 而您还没有 切换 到那个特定的 new tab/new window,否则您可能会得到 NoSuchElement异常。
  5. 如果您已切换到 iframe 并且所需的新元素不在同一个 iframe 上下文中,那么首先 switch to default content 然后与之交互。

切换到框架:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "frame XPath here")))

切换到默认内容:

driver.switch_to.default_content() 

如果您使用显式等待,那么您还需要下面的导入。

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

Aan <inpt> 元素是 clickable 元素,最适合定位需要引入任何 clickable 元素 WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#nickname[name='nickname'][placeholder='Nickname'][data-functional-selector='username-input']")))
    
  • 使用 XPATH:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='nickname' and @name='nickname'][@placeholder='Nickname' and @data-functional-selector='username-input']")))
    
  • 注意:您必须添加以下导入:

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

参考资料

您可以在以下位置找到关于 的一些相关讨论: