使用Chrome时Selenium"selenium.common.exceptions.NoSuchElementException"

val*_*rse 7 python selenium google-chrome chromium selenium-chromedriver

我正在尝试在Chrome上使用Selenium 播放QWOP,但我一直收到以下错误:

selenium.common.exceptions.NoSuchElementException: 
Message: no such element: Unable to locate element
{"method":"id","selector":"window1"
(Session info: chrome=63.0.3239.108
(Driver info: chromedriver=2.34.522913
(36222509aa6e819815938cbf2709b4849735537c), platform=Linux 4.10.0-42-generic x86_64)
Run Code Online (Sandbox Code Playgroud)

使用以下代码时:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time

browser = webdriver.Chrome()
browser.set_window_size(640, 480)
browser.get('http://www.foddy.net/Athletics.html?webgl=true')
browser.implicitly_wait(10)

canvas = browser.find_element_by_id("window1")

canvas.click()

while (True):
    action = ActionChains(browser)
    action.move_to_element(canvas).perform()
    canvas.click()
    canvas.send_keys("q")
Run Code Online (Sandbox Code Playgroud)

相同的代码在Firefox上完美运行,但由于我想使用chrome的功能在无头模式下运行webgl游戏,我无法真正切换到Firefox.

有什么办法让这个工作吗?

Deb*_*anB 8

NoSuchElementException

selenium.common.exceptions.NoSuchElementException俗称的NoSuchElementException定义为:

exception selenium.common.exceptions.NoSuchElementException(msg=None, screen=None, stacktrace=None)
Run Code Online (Sandbox Code Playgroud)

NoSuchElementException 基本上抛出2种情况如下:

根据API Docs,与其他任何文档一样selenium.common.exceptions,NoSuchElementException应包含以下参数:

  • 消息,屏幕,堆栈跟踪

        raise exception_class(message, screen, stacktrace)
    selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='create-portal-popup']/div[4]/div[1]/button[3]"}
      (Session info: chrome=61.0.3163.100)
      (Driver info: chromedriver=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT 10.0.10240 x86_64)
    
    Run Code Online (Sandbox Code Playgroud)

原因

NoSuchElementException的原因可能是以下任一情况:

  • 您采用的定位器策略未标识HTML DOM中的任何元素.
  • 您采用的定位器策略无法识别元素,因为它不在浏览器的视口中.
  • 您采用的定位器策略标识元素,但由于属性style ="display:none;"的存在而不可见..
  • 您采用的定位器策略不能唯一标识HTML DOM中的所需元素,并且当前会找到其他隐藏/不可见元素.
  • 您尝试查找的WebElement位于<iframe>标记内.
  • webdriver的实例看着外面的WebElement甚至之前的元素都看得到内本/ HTML DOM.

解决NoSuchElementException的解决方案可以是以下任一种:


这个用例

您看到了NoSuchElementException因为id定位器没有唯一标识画布.为了确定画布上,并click()在其上,你必须等待画布clickable和实现,你可以使用下面的代码块:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//canvas[@id='window1']"))).click()
Run Code Online (Sandbox Code Playgroud)