📜  move_by_offset – Selenium Python中的动作链(1)

📅  最后修改于: 2023-12-03 14:44:23.950000             🧑  作者: Mango

move_by_offset – Selenium Python中的动作链

动作链(ActionChains)是利用Selenium WebDriver模拟鼠标或键盘操作的工具之一,可以实现一些人手操纵难度较高的操作,如拖拽、滑动、双击等。

move_by_offset方法是ActionChains中的一个方法,可以用来将鼠标移动到某个元素的相对位置上。本文将详细介绍move_by_offset的用法。

语法
ActionChains(driver).move_by_offset(xoffset, yoffset).perform()
参数

xoffset:横向距离,单位为像素。

yoffset:纵向距离,单位为像素。

使用方法

使用move_by_offset方法前需要导入ActionChains

from selenium.webdriver.common.action_chains import ActionChains

然后创建ActionChains的实例,将需要操作的元素作为参数传入:

action = ActionChains(driver)

我们可以对这个操作链添加多个操作,最后通过perform方法执行:

action.move_by_offset(10, 20).perform()

其中的1020分别代表横向和纵向的距离。

示例

下面我们以在网页上拖拽一个元素为例,来演示move_by_offset的使用:

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

driver = webdriver.Chrome()

# 打开网页
driver.get("https://www.baidu.com")

# 找到左上角的“设置”元素
setting = driver.find_element_by_xpath('//*[@id="s-usersetting-top"]')
# 将鼠标移动到元素上
ActionChains(driver).move_to_element(setting).perform()

# 找到“搜索设置”元素
search_setting = driver.find_element_by_xpath('//*[@id="s-user-setting-menu"]/a[1]')
# 将鼠标移动到“搜索设置”元素上
ActionChains(driver).move_to_element(search_setting).perform()

# 等待加载完成
driver.implicitly_wait(10)

# 找到“搜索结果显示条数”元素
result_num = driver.find_element_by_xpath('//*[@id="nr"]')
# 将选项改为100条
ActionChains(driver).move_to_element(result_num).click().move_by_offset(0, 100).click().perform()

# 关闭浏览器
driver.quit()

这段代码会打开百度首页,将鼠标移动到左上角的“设置”按钮上,再移动到“搜索设置”按钮上,然后将搜索结果显示的条数改为100条。