原文:https://www.cnblogs.com/pythonClub/p/10491857.html
1
2
3
4
5
6
7
|
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()
# 鼠標右鍵點擊
|
需要注意的是,每次移動都是在上一次坐標的基礎上(即坐標值是累積的),如上的代碼實際運行時,點擊完左鍵再點擊右鍵,坐標會變成(400, 200)。
可以用封裝來抵消這種累積(點擊完之后將鼠標坐標恢復),代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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
)
# 右鍵點擊
|