首页 > 解决方案 > 为什么我在视口内得到坐标的 MoveTargetOutOfBoundsException?怎么修?

问题描述

使用以下代码:

elem = driver.find_element_by_xpath('/html/body/canvas')
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
actions.move_to_element_with_offset(elem, 185, -35).click().perform()

我无法导航到画布元素的所需部分并收到此错误:

MoveTargetOutOfBoundsException: move target out of bounds
(Session info: chrome=85.0.4183.102)

我的移动目标肯定在视口内,不需要滚动即可使其可点击。我正在使用 chromedriver 并使用画布的左上角作为我的像素坐标的起点move_to_element_with_offset()。有什么想法可以解决这个问题吗?我对在 python 中单击画布上的指定点的任何解决方案感兴趣,不需要使用相同的方法。

标签: pythonseleniumselenium-webdriverhtml5-canvasselenium-chromedriver

解决方案


move_to_element_with_offset()

move_to_element_with_offset()将鼠标移动指定元素的偏移量,其中偏移量相对于元素的左上角。

<canvas>因此,如果您打算按偏移量移动,则从元素的左上角开始(185, -35)

  • 右侧 185 个单位
  • 35个单位以上

将始终导致MoveTargetOutOfBoundsException.


解决方案

您可以使用正偏移量来向下移动,而不是向上移动的负偏移量,如下所示:

actions.move_to_element_with_offset(elem, 35, 35).click().perform()

参考

您可以在以下位置找到相关的详细讨论:


推荐阅读