首页 > 解决方案 > 为什么我不能用 Python 在 Selenium Chromedriver 中拖放?

问题描述

我无法使用最新的 Chromedriver 拖放 Selenium。selenium='3.141.0' python 3.7 Chrome = 74.0.3729.169 ChromeDriver =最新

下面的代码成功执行,但项目没有从源拖到目的地。我也没有收到任何错误。我一一尝试了以下所有解决方案,但根本没有工作。

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

cd = webdriver.Chrome('Chromedriver.exe')
cd.get('https://www.seleniumeasy.com/test/drag-and-drop-demo.html')
cd.maximize_window()

elements = cd.find_element_by_id('todrag')
drag_item = elements.find_elements_by_tag_name('span')
drag_to = cd.find_element_by_id('mydropzone')

# Solution 1 (not working)
for i in drag_item:
   action = ActionChains(cd)
   action.drag_and_drop(i, drag_to).perform() # this is not working

   # Solution 2 (not working)
   ActionChains(cd).click_and_hold(i).move_to_element(drag_to).release(
    drag_to).perform()


  # Solution 3 (not working, as you need to download the js files)
  jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js"
  with open("jquery_load_helper.js") as f:
    load_jquery_js = f.read()

 with open("drag_and_drop_helper.js") as f:
    js = f.read()
 cd.execute_async_script(load_jquery_js, jquery_url)

 cd.execute_script(js + "$(\'arguments[0]\').simulateDragDrop({ dropTarget: \"arguments[1]\"});", i, drag_to)

标签: pythonseleniumdrag-and-dropselenium-chromedriver

解决方案


我认为该网站有问题,因为我在网上找到的这个示例似乎有效:

import time
from selenium import webdriver
from selenium.webdriver import ActionChains

# Create chrome driver.
driver = webdriver.Chrome()

# Open the webpage.
driver.get("https://openwritings.net/sites/default/files/selenium-test-pages/drag-drop.html")

# Pause for 5 seconds for you to see the initial state.
time.sleep(5)

# Drag and drop to target item.
##################################
drag_item = driver.find_element_by_id("draggable")
target_item = driver.find_element_by_id("droppable")

action_chains = ActionChains(driver)
action_chains.drag_and_drop(drag_item, target_item).perform()
##################################

# Pause for 10 seconds so that you can see the results.
time.sleep(10)

# Close.
driver.quit()

希望该示例对您有所帮助!


推荐阅读