Selenium Python-拖放不适用于现场

时间:2020-01-16 14:52:33

标签: python python-3.x selenium drag-and-drop webdriver

我正在使用Selenium Webdriver最新版本,并且需要从CKeditor中将链接拖放到注释字段中,但不是IFrame。在我之前的测试中,它通过Robot拖放功能与Java和带有FF47的Selenium2一起使用。

现在,我需要使用最新版本的Selenium with Python3来执行此操作。我输入了此经过验证的代码,该代码应该可以工作,但是它将鼠标拖曳并保持住具有拖动链接的保持元素,因此其余测试将通过保持标题链接通过,该链接未放入CKeditor,而是在模拟鼠标单击时注释字段,它将在操作中变为活动状态,但保持元素不会掉入其中。仅手动单击鼠标会将链接放入注释,并重置鼠标保持状态。在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键,双击鼠标,按偏移量移动,重置动作,切换到框架,单击Javascript-无效,仍然相同。有人可以帮我做这个手术吗?鼠标仍然按住拖动的元素,直到测试结束,否则我将手动单击某处。

2 个答案:

答案 0 :(得分:1)

好的,所以我主要使用Javascript解决方案进行了所有尝试。使用元素或ID选择器尝试了SimulatorDragDrop,使用JQuery尝试了SimulationDragDrop,针对JQuery尝试了executeAsync,但没有任何反应。甚至在其他拖放情况下都尝试过此操作,但这并不起作用。

最近的解决方案是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使用窗口坐标,而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()

答案 1 :(得分:0)

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()