selenium-模拟鼠标拖拽

1、从一个元素拖拽到另一个元素:
from selenium import webdriver
from selenium.webdriver import ActionChains
import time

browser = webdriver.Chrome()
try:
    browser.get("http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
    browser.maximize_window()

    browser.switch_to.frame('iframeResult')

    source = browser.find_element_by_id('draggable')
    target = browser.find_element_by_id('droppable')

    print(source)
    print(target)
    actions = ActionChains(browser)
    actions.drag_and_drop(source, target)
    actions.perform()

    alert = browser.switch_to.alert
    print(alert)
    time.sleep(3)
    alert.dismiss()

    time.sleep(5)
except Exception as e:
    print(e)
finally:
    browser.quit()
    print('OK')

运行结果:
拖拽前:

selenium-模拟鼠标拖拽_第1张图片
拖拽后:

selenium-模拟鼠标拖拽_第2张图片

2、按着坐标拖拽:

比如操作canvas元素:

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

def move_by_offset(webdriver):
    canvas = webdriver.find_element_by_id("canvas")
    drawing = ActionChains(webdriver)\
        .click_and_hold(canvas)\
        .move_by_offset(-10, -15)\
        .move_by_offset(20, 32)\
        .move_by_offset(10, 25)\
        .release()
    drawing.perform() 

这样鼠标的轨迹就会按着代码中坐标的指示。
比如使用画笔拖拽:
selenium-模拟鼠标拖拽_第3张图片

你可能感兴趣的:(python)