Python 硒:元素不可点击......其他元素会收到点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35636155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:43:44  来源:igfitidea点击:

Selenium: Element not clickable ... Other Element Would Receive Click

pythondjangoseleniumselenium-webdriverdjango-testing

提问by jejy2343

When running Selenium tests on my Django project, I've started to get the error:

在我的 Django 项目上运行 Selenium 测试时,我开始收到错误消息:

selenium.common.exceptions.WebDriverException: Message: Element is not clickable at point (61, 24.300003051757812). Other element would receive the click: <a class="navbar-brand" href="#"></a>

It is odd for two reasons: First, the tests previously passed and I have not edited that part of the code base. Second, when the Selenium-driven Firefox Window pops up and I maximize the page, the tests pass. But when I let the Selenium tests run with the Firefox browser not maximized, they fail.

这很奇怪,有两个原因:首先,之前通过的测试我没有编辑代码库的那部分。其次,当 Selenium 驱动的 Firefox 窗口弹出并且我最大化页面时,测试通过。但是当我让 Selenium 测试在 Firefox 浏览器未最大化的情况下运行时,它们会失败。

I'm not using any fancy javascript (just the basic Bootstrap 3 template), just plain old html and css. I'm using Django 1.9 on Python 3.4. I've run pip to check for upgrades to Selenium, and I'm up to date.

我没有使用任何花哨的 javascript(只是基本的 Bootstrap 3 模板),只是简单的旧 html 和 css。我在 Python 3.4 上使用 Django 1.9。我已经运行 pip 来检查 Selenium 的升级,并且我是最新的。

Here is a pastebin linkto the html of the output of my view and template.

这是我的视图和模板输出的 html 的pastebin 链接

One of the failing tests is:

失败的测试之一是:

def test_create_task_and_check_that_it_shows_up_in_the_task_manager_index_and_filter(self):
        # Create user
        self.user = User.objects.get(username=test_superuser_username)
        # Log the user in
        self.log_user_in(user_object=self.user, password=test_superuser_password)
        self.browser.implicitly_wait(10)
        # Pull up the main task manager page
        self.browser.get(str(self.live_server_url) + reverse('task_manager:index'))
        # Make sure we go to the task manager index
        task_index_url = str(self.live_server_url) + reverse('task_manager:index')
        self.browser.get(task_index_url)
        self.browser.implicitly_wait(4)
        self.assertTrue(str(task_index_url) == self.browser.current_url,
                        msg=('Assertion that current_url is %s failed. Current_url is %s' %
                             (str(reverse('task_manager:index')), self.browser.current_url)))
        # Click the 'add task' button on the sidebar
        add_task_taskbar_button = self.browser.find_element_by_name('add_task_sidebar_link')
        add_task_taskbar_button.click()

The last line produces the error:

最后一行产生错误:

ERROR: test_create_task_and_check_that_it_shows_up_in_the_task_manager_index_and_filter (tasks.tests.test_functional.SeleniumTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/mint/Python_Projects/[project_name]/tasks/tests/test_functional.py", line 94, in test_create_task_and_check_that_it_shows_up_in_the_task_manager_index_and_filter
    add_task_taskbar_button.click()
  File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/selenium/webdriver/remote/webelement.py", line 75, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/selenium/webdriver/remote/webelement.py", line 469, in _execute
    return self._parent.execute(command, params)
  File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
  File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Element is not clickable at point (61, 24.300003051757812). Other element would receive the click: <a class="navbar-brand" href="#"></a>

采纳答案by Makjb lh

Your Answer lies within your question.

你的答案就在你的问题中。

  1. Error says 'add_task_sidebar_link' not clickable at point - (61, 24.300003051757812)This is where another element is - Other element would receive the click: <a class="navbar-brand" href="#"></a>where the click is being attempted. Since you did not maximize the browser, you are not able to get the point co ordinates correctly.
  2. In order for future tests to not break, pls scroll to that element. Refer to this post (Selenium python unable to scroll down). Check Action chains (http://selenium-python.readthedocs.org/api.html#module-selenium.webdriver.common.action_chains)
  1. 错误显示“add_task_sidebar_link”not clickable at point - (61, 24.300003051757812)这是另一个元素Other element would receive the click: <a class="navbar-brand" href="#"></a>所在的位置 - 尝试点击的位置。由于您没有最大化浏览器,因此您无法正确获取点坐标。
  2. 为了将来的测试不会中断,请滚动到该元素。请参阅此帖子(Selenium python 无法向下滚动)。检查操作链(http://selenium-python.readthedocs.org/api.html#module-selenium.webdriver.common.action_chains

回答by aneroid

This has more to do with elements 'covering' each other. Which makes sense if it's happening on non-maximized windows. Could also happen if there was a popup/floating div or another element which covering the element you're actually trying to click on.

这更多地与元素“覆盖”彼此有关。如果它发生在非最大化窗口上,这是有道理的。如果有一个弹出/浮动 div 或其他元素覆盖了您实际尝试单击的元素,也可能发生这种情况。

Remember, selenium is mimicking the user, so you can't normally do an action which the user wouldn't have been able to do - like click on an element which is covered by another.

请记住,selenium 正在模仿用户,因此您通常无法执行用户无法执行的操作 - 例如单击被另一个元素覆盖的元素。

A potential workaround for this would be to use Javascript to find the element and click on it. Example here:

一个潜在的解决方法是使用 Javascript 来查找元素并单击它。这里的例子

labels = driver.find_elements_by_tag_name("label")
inputs = driver.execute_script(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
    "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels)

回答by Sarabjit Singh

In my current Capybara project, I often get "Element not clickable" errors. The reason for this kind of error is that web page doesn't loads well enough to locate the element. As you have mentioned that the tests previously passed and you haven't edited that part of the code base, So you can do the following things to get pass through this:

在我当前的 Capybara 项目中,我经常收到“元素不可点击”错误。出现这种错误的原因是网页加载不够好,无法定位元素。正如您所提到的,之前通过的测试并且您尚未编辑代码库的那部分,因此您可以执行以下操作来通过此:

  1. Put some more wait time before locating "add_task_sidebar_link". So that the page loads fully.
  2. Still if the test fails even after adding wait, then add some method to take screenshot before clicking the element. This will help debugging the test.
  1. 在找到“add_task_sidebar_link”之前多等待一些时间。以便页面完全加载。
  2. 如果添加等待后测试仍然失败,则在单击元素之前添加一些方法来截取屏幕截图。这将有助于调试测试。

回答by Florent B.

Since recently the Firefox driver checks that the element at the clicking position is the element supposed to be clicked. This error means that when the driver tries to click the element, an other one is on top of it. Unfortunatelly, the driver doesn't automatically scroll the containers and raises this error instead.

最近 Firefox 驱动程序检查点击位置的元素是否是应该被点击的元素。此错误意味着当驱动程序尝试单击该元素时,另一个元素位于该元素之上。不幸的是,驱动程序不会自动滚动容器而是引发此错误。

On way to handle this issue is to scroll the element in the center of the screen and try to click again. Monkey patch for the click method :

处理此问题的方法是滚动屏幕中央的元素并尝试再次单击。单击方法的猴子补丁:

JS_SCROLL_ELEMENT_CENTER_WINDOW = """\
  var element = arguments[0];
  element.scrollIntoView(true);
  var y = (window.innerHeight - element.offsetHeight) / 2;
  if (y > 0) {
    for (var e=element; e; e=e.parentElement) {
      if (e.scrollTop) {
        var yy = Math.min(e.scrollTop, y);
        e.scrollTop -= yy;
        if ((y -= yy) < 1)
          return;
      }
    }
    window.scrollBy(0, -y);
  }
  """

def click(self):
  try:
    self._execute(Command.CLICK_ELEMENT)
  except:
    self._parent.execute(Command.EXECUTE_SCRIPT, \
      {'script': JS_SCROLL_ELEMENT_CENTER_WINDOW, 'args': [self]})
    self._execute(Command.CLICK_ELEMENT)

from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.remote.command import Command
WebElement.click = click

回答by Major Major

Extremely late to the party, but I have an extremely simple solution that worked for me. Instead of doing .click(), simply do

聚会非常晚,但我有一个非常简单的解决方案,对我有用。而不是做 .click(),只需做

.send_keys(selenium.webdriver.common.keys.Keys.SPACE)

With the element selected, the spacebar can toggle the selection. Worked for me!

选择元素后,空格键可以切换选择。为我工作!

回答by Will Rus

Ran into a similar problem (same error) and tried Major Major's solution above using send_keys + sending the space bar to simulate a click rather than a mouse click.

遇到了类似的问题(相同的错误),并使用 send_keys + 发送空格键来模拟点击而不是鼠标点击,尝试了上面的 Major Major 的解决方案。

Major Major's solution:

Major Major的解决方案:

.send_keys(selenium.webdriver.common.keys.Keys.SPACE)

I hit a new error trying to run this, pointing at 'selenium'. Removing that keyword from the code fixed the issue, and allowed me to click the element.

我在尝试运行它时遇到了一个新错误,指向“硒”。从代码中删除该关键字解决了该问题,并允许我单击该元素。

Final successful code snippet used:

使用的最终成功代码片段:

my_variable = driver.find_element_by_xpath('//*[@id="myId"]') #this is the checkbox
my_variable.send_keys(webdriver.common.keys.Keys.SPACE)

回答by rp2017

I had the same issue: due to a pop-up window, the element I had to click on would drift off the screen and become unclickable.

我遇到了同样的问题:由于弹出窗口,我必须点击的元素会从屏幕上漂移并变得无法点击。

Scrolling the page to the element worked.

将页面滚动到元素有效。

In Python:

在 Python 中:

elem = driver.find_element_by_tag_name("html")
elem.send_keys(Keys.END)