Selenium Python - 拖放无法进入现场

Selenium Python - drag and drop not working into field

我正在使用最新版本的 Selenium Webdriver,我需要将 link 一个元素拖放到 CKeditor 的注释字段中,但它不是 IFrame。从我之前的测试来看,它是通过机器人拖放功能与 Java 和 Selenium2 以及 FF47 一起工作的。

现在,我需要使用带有 Python3 的最新版本的 Selenium 执行此操作。我放了这段经过验证的代码,它应该可以工作,但是它会把我的鼠标卡在拖动的 link 的保持元素上,所以测试的其余部分将通过保持标题 link,它不会被放入 CKeditor ,但是当我模拟鼠标点击一个注释字段时,它会从操作中变为活动状态,但持有元素不会掉入。只有手动单击鼠标才会将 link 放入注释中并重置鼠标保持。使用 Ubuntu 18.04 amd64 Firefox 70 和 GChrome 77 进行测试 - 结果相同。

代码如下:

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

driver = webdriver.Firefox()
driver.get(URL)
alink_from = driver.find_element_by_xpath(TITLE)
anotation_body = driver.find_element_by_xpath(TFIELD)
# 1. alternative
ActionChains(driver).drag_and_drop(alink_from, anotation_body).click(anotation_body).perform()
# 2. alternative
ActionChains(driver).click_and_hold(alink_from).move_to_element(anotation_body).release().click(anotation_body).perform()

还尝试按 Enter 键、双击鼠标、按偏移量移动、重置动作、切换到框架、Java单击脚本 - 没有任何效果,还是一样。有人可以帮我做这个手术吗?在测试结束之前,鼠标仍然按住拖动的元素,否则我将手动单击某处。

ActionChains 按照插入的顺序执行操作:单击并按住元素,将其放到目标字段中,然后才单击该字段。如果单击后该字段变为活动状态,请先执行此操作

ActionChains(driver).click(anotation_body).drag_and_drop(alink_from, anotation_body).perform()
# or
anotation_body.click()
ActionChains(driver).drag_and_drop(alink_from, anotation_body).perform()

好的,所以我尝试了大部分使用 Javascript 解决方案的方法。尝试使用元素或 ID 选择器模拟拖放,尝试使用 JQuery 模拟拖放,尝试使用 JQuery 执行异步,但没有任何反应。甚至在其他拖放情况下也试过这个,但它不起作用。

最近的解决方案是 JS 拖放,它会拖拽元素,但不会放下: https://ynot408.wordpress.com/2011/09/22/drag-and-drop-using-selenium-webdriver/

driver.execute_script(js + "simulate(arguments[0],'mousedown',0,0);",alink_from)
driver.execute_script(js + "simulate(arguments[0],'mousemove',arguments[1],arguments[2]);",alink_from,xto,yto)
driver.execute_script(js + "simulate(arguments[0],'mouseup',arguments[1],arguments[2]);",alink_from,xto,yto)

几个小时后,我终于通过使用库 PyAutoGUI 找到了解决方案!但这将需要获得不同的坐标,因为 PyAutoGUI 使用 window 坐标而 Selenium 使用浏览器坐标。问题是,您需要关注将被拖入目标的目标元素,但它需要将鼠标向上移动到目标,然后向上单击到目标。

此库也需要安装(例如 Ubuntu):

sudo apt-get install python3-tk
pip3 install pyautogui

代码如下:

import time
import pyautogui

height=driver.get_window_size()['height']
browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')
xf = alink_from.location['x']
yf = alink_from.location['y']
act_y_from = yf%height
scroll_Y_from= yf/height
try:
    driver.execute_script("window.scrollTo(0, "+str(scroll_Y_from*height)+")")
except Exception as err:
    print("Exception")
pyautogui.moveTo(xf,act_y_from+browser_navigation_panel_height)

xto = anotation_body.location['x']
yto = anotation_body.location['y']
act_y_to = yto%height
scroll_Y_to = yto/height
pyautogui.dragTo(xto+1,act_y_to+browser_navigation_panel_height)
time.sleep(2)
pyautogui.mouseUp()
time.sleep(2)
pyautogui.click()