Python+selenium点击网页上指定坐标

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

dr = webdriver.Chrome()
dr.get('http://www.baidu.com')
ActionChains(dr).move_by_offset(200, 100).click().perform() # 鼠标左键点击, 200为x坐标, 100为y坐标
ActionChains(dr).move_by_offset(200, 100).context_click().perform() # 鼠标右键点击
# 通过获取坐标值点击
sx = dr.find_element_by_id('pro-operation')
x = sx.location['x']
y = sx.location['y']
ActionChains(dr).move_by_offset(x, y).double_click().perform() # 双击
ActionChains(dr).move_to_element(sx).perform() # 鼠标移到悬停元素上

需要注意的是,每次移动都是在上一次坐标的基础上(即坐标值是累积的),如上的代码实际运行时,点击完左键再点击右键,坐标会变成(400, 200)。

可以用封装来抵消这种累积(点击完之后将鼠标坐标恢复),代码如下:


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

def click_locxy(dr, x, y, left_click=True):
    '''
    dr:浏览器
    x:页面x坐标
    y:页面y坐标
    left_click:True为鼠标左键点击,否则为右键点击
    '''
    if left_click:
        ActionChains(dr).move_by_offset(x, y).click().perform()
    else:
        ActionChains(dr).move_by_offset(x, y).context_click().perform()
    ActionChains(dr).move_by_offset(-x, -y).perform()  # 将鼠标位置恢复到移动前

if __name__ == "__main__":
    dr = webdriver.Chrome()
    dr.get('http://www.baidu.com')
    click_locxy(dr, 100, 0) # 左键点击
    click_locxy(dr, 100, 100, left_click=False) # 右键点击

ActionChains方法列表

click(on_element=None) ——单击鼠标左键

click_and_hold(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) ——拖拽到某个坐标然后松开

key_down(value, element=None) ——按下某个键盘上的键

key_up(value, element=None) ——松开某个键

move_by_offset(xoffset, yoffset) ——鼠标从当前位置移动到某个坐标

move_to_element(to_element) ——鼠标移动到某个元素

move_to_element_with_offset(to_element, xoffset, yoffset) ——移动到距某个元素(左上角坐标)多少距离的位置

perform() ——执行链中的所有动作

release(on_element=None) ——在某个元素位置松开鼠标左键

send_keys(*keys_to_send) ——发送某个键到当前焦点的元素

send_keys_to_element(element, *keys_to_send) ——发送某个键到指定元素 

参考:https://www.cnblogs.com/haiya2019/p/10627740.html

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值