from selenium.webdriver import ActionChains
action = ActionChains(driver) # 然后把driver作为参数,实例化一个action对象
练习地址:https://sahitest.com/demo/
悬停例子(百度首页)
action.move_to_element(ele).perform()
from selenium import webdriver
import time
# 创建浏览器驱动对象
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 访问网址
driver.get("https://www.baidu.com/")
"""
1. 导入
"""
from selenium.webdriver import ActionChains
"""
2. 实例化一个action对象
"""
action =ActionChains(driver)
"""
悬停到百度首页,的【更多】按钮上面
"""
ele = driver.find_element(By.XPATH,' //*[contains(text(),"更多")]')
action.move_to_element(ele).perform()
拖动(a到b)
使用:drag_and_drop
from selenium import webdriver
import time
# 创建浏览器驱动对象
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 访问网址
driver.get("https://sahitest.com/demo/dragDropMooTools.htm")
"""
1. 导入
"""
from selenium.webdriver import ActionChains
"""
2. 实例化一个action对象
"""
action =ActionChains(driver)
"""
把ele元素,拖动到ele2的元素位置
"""
ele1 = driver.find_element(By.CSS_SELECTOR,'#dragger.drag')
ele2 = driver.find_element(By.CSS_SELECTOR,'div.item') # 第一个 用 :nth-child() 不行?
ele4 = driver.find_element(By.XPATH,' //*[contains(text(),"Item 4")]') # 第4个
# 睡一秒后,开始拖动
time.sleep(1)
action.drag_and_drop(ele1,ele2).perform() # 拖动到1
time.sleep(0.5)
action.drag_and_drop(ele1,ele4).perform() # 拖动到4
拖动(a便宜一个坐标量)
使用:drag_and_drop_by_offset
使用了一点串改,让网站不知道是selenium控制的webdriver
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",{
"source":"""Object.defineProperty(navigator,'webdriver',{get: () => undefined})"""
})
from selenium import webdriver
import time
# 创建浏览器驱动对象
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 执行js,串改一下,让网站不知道是自动化的操作。
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",{
"source":"""Object.defineProperty(navigator,'webdriver',{get: () => undefined})"""
})
# 访问网址
driver.get("http://vip.ytesting.com/")
driver.maximize_window()
from selenium.webdriver import ActionChains
action =ActionChains(driver)
"""计算距离"""
ele = driver.find_element(By.CSS_SELECTOR,"#nc_1_n1z") # 滑块元素
ele_t =driver.find_element(By.ID,'nc_1__scale_text') # 滑动条
distance = ele_t.rect['width'] -ele.rect['width']
print(distance)
action.drag_and_drop_by_offset(ele,distance,0).perform()