selenium——鼠标操作ActionChains:点击、滑动、拖动

from selenium.webdriver import ActionChains


1、鼠标点击

click:鼠标左击
double_click:鼠标双击
context_click:鼠标右击

btn = driver.find_element_by_id('su')
# 第一步:创建一个鼠标操作的对象
action = ActionChains(driver)
# 第二步:进行点击动作(事实上不会进行操作,只是添加一个点击的动作)
action.click(btn)
# 第三步:执行动作
action.perform()

2、鼠标移动

driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
driver.implicitly_wait(5)

# 定位设置元素
set_ele = driver.find_element_by_xpath("//div[@id='u1']//a[text()='设置']")
# 第一步:创建一个鼠标操作的对象
action = ActionChains(driver)
# 第二步:进行移动
action.move_to_element(set_ele)
# 第三步:执行动作
action.perform()

# 三行代码写成一行:支持链式调用
ActionChains(driver).move_to_element(set_ele).perform()

# 等待高级设置可点击
WebDriverWait(driver,5,0.2).until(
    EC.element_to_be_clickable((By.XPATH,"//a[text()='高级搜索']"))
).click()

3、鼠标滑动

# 选择拖动滑块的节点
sli_ele = driver.find_element_by_id('tcaptcha_drag_thumb')
# ------------鼠标滑动操作------------
action = ActionChains(driver)
# 第一步:在滑块处按住鼠标左键
action.click_and_hold(sli_ele)
# 第二步:相对鼠标当前位置进行移动
action.move_by_offset(100,0)
# 第三步:释放鼠标
action.release()
# 执行动作
action.perform()

4、鼠标在一个元素上拖动到另一个元素

s = WebDriverWait(driver, 30, 0.5).until(
    EC.visibility_of_element_located((By.ID, 'draggable'))
)
t = WebDriverWait(driver, 30, 0.5).until(
    EC.visibility_of_element_located((By.ID, 'droppable'))
)
# ------------鼠标滑动操作------------
action = ActionChains(driver)
# 第一步:拖动元素
action.drag_and_drop(s, t)
# 执行动作
action.perform()

猜你喜欢

转载自www.cnblogs.com/erchun/p/12906324.html