You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Selenium点击指定绝对X、Y坐标(无DOM/XPATH)

直接通过绝对坐标点击页面元素的方案

针对不依赖DOM元素/XPath,仅通过绝对X、Y坐标完成点击的需求,以下是不同Selenium语言绑定下的实用实现方案:

Python 实现

借助ActionChains类,先将鼠标从页面左上角(0,0)偏移到目标坐标后执行点击:

from selenium.webdriver.common.action_chains import ActionChains

# 替换为你的目标坐标
target_x = 150
target_y = 300

actions = ActionChains(driver)
# 移动到目标坐标并点击
actions.move_by_offset(target_x, target_y).click().perform()
# 执行后建议将鼠标移回初始位置,避免影响后续操作
actions.move_by_offset(-target_x, -target_y).perform()

需要双击的话,将click()替换为double_click()即可。

Java 实现

使用Actions类的偏移移动与点击组合操作:

import org.openqa.selenium.interactions.Actions;

int targetX = 150;
int targetY = 300;

Actions actions = new Actions(driver);
// 定位到目标坐标并点击
actions.moveByOffset(targetX, targetY).click().build().perform();
// 重置鼠标位置
actions.moveByOffset(-targetX, -targetY).build().perform();

C# 实现

通过Actions类完成坐标偏移与点击:

using OpenQA.Selenium.Interactions;

int targetX = 150;
int targetY = 300;

Actions actions = new Actions(driver);
actions.MoveByOffset(targetX, targetY).Click().Perform();
// 恢复鼠标初始位置
actions.MoveByOffset(-targetX, -targetY).Perform();

关键注意事项

  • 坐标以浏览器窗口左上角为原点,若页面存在滚动,需先将目标区域滚动至可视范围,否则点击会失效
  • 部分浏览器需启用原生事件支持,以Chrome为例,初始化驱动时可添加配置:
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--enable-native-events")
    driver = webdriver.Chrome(options=options)
    
  • 若之前的方案接近但无效,优先排查页面滚动导致的坐标偏移、浏览器与驱动版本不兼容问题

内容的提问来源于stack exchange,提问作者prljav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:25:24