【发布时间】:2020-02-05 14:09:09
【问题描述】:
我正在努力在私有网络应用程序的 python 中使用 Selenium 执行拖放或单击并按住操作。
我尝试在此处的公开示例中重现我的错误: http://the-internet.herokuapp.com/drag_and_drop
下面是我的拖放/单击并按住的基本代码
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('http://the-internet.herokuapp.com/drag_and_drop')
dragged = driver.find_element(By.ID, "column-a")
dropped = driver.find_element(By.ID, "column-b")
#Drag and drop
actions = ActionChains(driver)
actions.drag_and_drop(dragged, dropped).perform()
#column A is selected but not dragged
#Click and hold
actions = ActionChains(driver)
actions.move_to_element(dragged).click_and_hold().move_to_element(dropped).release().perform()
#Same result : column a is selected but not dragged
通过 stackoverflow 搜索,我发现了一个使用 javascript 的公共示例的“解决方案”。 How to simulate HTML5 Drag and Drop in Selenium Webdriver?
import os
with open(os.path.abspath('C:/Users/Admin/PycharmProjects/AutoTestIntro/drag_and_drop_helper.js'), 'r') as js_file:
line = js_file.readline()
script = ''
while line:
script += line
line = js_file.readline()
driver.execute_script(script+"$('#column-a').simulateDragDrop({ dropTarget: '#column-b'});")
这完美地直接在 python 中工作,但要求拖放的元素有 id。我目前正在从事的私人项目并非如此。
我对 Selenium 做错了什么吗? JS中是否有任何解决方法来指定xpath而不是id?
【问题讨论】:
-
“拖拽元素”的目的地是低于还是高于原位置?
-
它们在提供的示例中完全相同。
-
发布你需要获取的元素的html。他们正在使用 css 选择器,这是一个列表。 w3schools.com/cssref/css_selectors.asp
-
嗨 Jortega,感谢您的回答,但我想我不明白您的意思。我的示例中提供的这个演示网站中提供了所有内容:the-internet.herokuapp.com/drag_and_drop 我尝试使用 id、css 选择器、xpath 进行选择.... 没有工作。你可以在演示网站上试试吗?
-
如果您可以提供 html,我们可以在 CSS 中构建您需要的 xpath。我无法让辅助函数
simulateDragDrop接受 xpath.... 没有完全重建它。
标签: python selenium drag-and-drop