python selenium模拟拖拽滑块如何生效?

from selenium import webdriver 
import time 
from selenium.webdriver.common.action_chains import ActionChains # 滑块,拖拽行为模拟

_driver = webdriver.Chrome()
_driver.get('https://www.jq22.com/yanshi3990')
_driver.implicitly_wait(15)

time.sleep(10)
try:
    ele = _driver.find_element_by_xpath('//*[@id="#drag2"]')
    print('开始执行滑块拖拽', ele)
    Action = ActionChains(_driver)
    Action.click_and_hold(ele).perform() # 按住元素
    Action.move_by_offset(258, 0).perform() # 拖动指定偏移量
    Action.pause(0.5).release().perform()# 释放滑块
    print('执行滑块拖拽完毕', ele)
except:
    print('啥都没干!')
    pass

元素一直无法拖动, 帮忙改一改让元素模拟拖拽,也不知道是哪里的问题, 拖拽一直没有效果

image.png

补充:
代码执行后元素是不会执行拖动的, 而是鼠标进入浏览器后才会突然的移动位置。不知道大家有没有遇到相同的情况?

网上查了一圈, 说是 ActionChains 这个方法不支持html5元素?
https://icode.best/i/18063934...

改用 import pyautogui 就可以模拟拖拽了

阅读 2.1k
1 个回答

emm,这个问题很像python中最经典的一个小项目,贪吃蛇游戏。一般这类问题改下等待时间和偏移量就可以解决,所以,我在你的代码上改了一些东西(改动的地方不多),可以参考:

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

_driver = webdriver.Chrome()
_driver.get('https://www.jq22.com/yanshi3990')
_driver.implicitly_wait(15)

time.sleep(10)
try:
    ele = _driver.find_element_by_id('drag2')  # 使用id定位元素
    print('开始执行滑块拖拽', ele)
    Action = ActionChains(_driver)
    Action.click_and_hold(ele).perform()  # 按住元素
    Action.move_by_offset(150, 0).perform()  # 拖动指定偏移量(根据实际情况进行调整)
    Action.pause(0.5).release().perform()  # 释放滑块
    print('执行滑块拖拽完毕', ele)
except:
    print('啥都没干!')
    pass
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题