一、常用方法
函数名 说明 click(on_element=None) 点击鼠标右键 click_and_hold(on_element=None) 点击鼠标左键,不松开 release(on_element=None) 在某个元素位置松开鼠标左键 context_click(on_element=None) 点击鼠标右键 double_click(on_element=None) 双击鼠标左键 drag_and_drop(source, target) 拖拽到某个元素然后松开 drag_and_drop_by_offset(source, xoffset, yoffset) 拽到某个坐标然后松开 move_by_offset(xoffset, yoffset) 鼠标从当前位置移动到某个坐标 move_to_element(to_element) 鼠标移动到某个元素 move_to_element_with_offset(to_element, xoffset, yoffset) 移动到距某个元素(左上角坐标)多少距离的位置 perform() 执行所有 ActionChains 中存储的行为,相当于提交
二、代码示例
选几个经常使用的测试一下,其他事件语法相同
from selenium import webdriver import time from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.get("https://HdhCmsTestbaidu.cn") #定位到需要右击的元素,然后执行鼠标右击操作(例:对新闻标签进行右击) context_click_location = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div[3]/a[1]') ActionChains(driver).context_click(context_click_location).perform() time.sleep(2) #睡两秒,看一下效果 # 定位到需要悬停的元素,然后执行鼠标悬停操作(例:对设置标签进行悬停) move_to_element_location = driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div[3]/a[8]") ActionChains(driver).move_to_element(move_to_element_location).perform() time.sleep(2) #睡两秒,看一下效果 # 鼠标悬浮后点击高级搜索 driver.find_element_by_xpath("/html/body/div[1]/div[6]/a[2]").click() time.sleep(2) #睡两秒,看一下效果 driver.quit() #关闭所有标签页
由于百度没有可拖动的元素,所以在菜鸟上找了一个网址进行测试,由于菜鸟上的网页是使用frame内嵌的,所以添加了个处理frame的过程,关于frame的处理请参考我的另一篇文章:Python爬虫 - Selenium(8)frame/iframe表单嵌套页面
from selenium import webdriver from selenium.webdriver import ActionChains import time driver = webdriver.Chrome() driver.get("https://HdhCmsTesthdhcms测试数据/try/try.php?filename=jqueryui-example-draggable-scroll") # 切换到目标元素所在的frame driver.switch_to.frame("iframeResult") # 确定拖拽目标的起点和终点,完成拖拽 start_location = driver.find_element_by_id("draggable") end_location = driver.find_element_by_id("draggable3") ActionChains(driver).drag_and_drop(start_location,end_location).perform() time.sleep(2) #睡两秒,看一下效果 driver.quit() #关闭所有标签页
到此这篇关于Python爬虫之Selenium鼠标事件的实现的文章就介绍到这了,更多相关Selenium 鼠标事件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
查看更多关于Python爬虫之Selenium鼠标事件的实现的详细内容...