You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Chrome拖拽功能失效,用pyautogui实现的解决方案

解决Selenium无法实现拖拽功能的方案

在测试目标网站的拖拽功能时,Selenium官方提供的各类拖拽方法(如drag_and_drop、drag_and_drop_by_offset,以及click_and_hold链式操作等)均无法生效,仅有的可行方案是执行JS脚本。经过研究,通过结合pyautogui可以实现有效的拖拽功能,具体代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pyautogui

driver = webdriver.Chrome()
driver.get('https://the-internet.herokuapp.com/drag_and_drop')
driver.implicitly_wait(10)

driver.set_window_size(800, 450)

win_size = driver.get_window_size()

source = driver.find_element(By.CSS_SELECTOR, "#column-a")
target = driver.find_element(By.CSS_SELECTOR, "#column-b")

element_size = source.size

source_location = source.location
target_location = target.location

inner_width = driver.execute_script("return window.innerWidth;")
inner_height = driver.execute_script("return window.innerHeight;")

offset_width = win_size['width'] - inner_width + element_size['width'] / 2
offset_height = win_size['height'] - inner_height + element_size['height'] / 2

# ### Print Statememts used for Debbug ###
# print(f"actual size is {win_size} ,ineer size is {inner_width}, {inner_height}")
# print(source_location, target_location)
# print(element_size, f"the offsets are {offset_width} and {offset_height}")

pyautogui.moveTo(source_location['x'] + offset_width, source_location['y'] + offset_height)
pyautogui.mouseDown()

pyautogui.moveTo(target_location['x'] + offset_width, target_location['y'] + offset_height, duration=3)
pyautogui.mouseUp()

# ###  Assertion to check in case you dont wanna look and just run the test ###
# ###  Find the moved item, get the new location  ###
# ###  Assert that initial location and location after move are not the same => Drag and Drop action is a success  ###
# source_moved = driver.find_element(By.XPATH, '//div[@class="column"]/header[text()="A"]')
# source_newlocation = source_moved.location
# assert source_location != source_newlocation

time.sleep(1)

driver.quit()
  • 必须将显示器缩放设置为100%,否则会导致鼠标位置计算错误,拖拽失败。

内容的提问来源于stack exchange,提问作者dbeniamin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 21:58:19