MoveTargetOutOfBoundsException
在使用 Selenium 开发爬虫对网页元素进行拖动操作的过程中,出现了如下异常信息:
selenium.common.exceptions.MoveTargetOutOfBoundsException: Message: move target out of bounds
从异常信息可以知道,是因为我们拖动的目标元素超出了 html 父元素的边界。
client = webdriver.Chrome()
client.get('你的爬虫目标网址')
time.sleep(5)
# 事件参数对象
actionChains = ActionChains(client)
# 捕捉滑块元素
slider_btn = client.find_element(By.ID, 'slider')
# 观察网站滑块移动的长度和位置
actionChains.click_and_hold(slider_btn)
actionChains.move_by_offset(220,300)
actionChains.release()
actionChains.perform()
time.sleep(5)
client.quit()
以上述的 Python 代码为例,move_by_offset 函数拖动时,Y 轴的坐标值一旦超出了 slider_btn 父元素的右边界就会引发 Selenium: move target out of bounds 异常。
要避免这种错误也简单,仔细分析网页上要拖动的元素上下左右的边界值(注意:这里是从要拖动的元素起始位置累加的值),使用 Selenium 进行拖动操作时不要超出父元素边界即可。