前言
相信大家在使用selenium做網頁自動化時,會遇到如下這樣的一個場景:
在你使用get訪問某一個網址時,會在頁面中彈出如上圖所示的彈出框。
首先想到是利用Alert類來處理它。
然而,很不幸,Alert類處理的結果就是沒有結果,並不能夠將這個彈出框關閉掉。
無法用處理alert的方式來關閉該彈出框,不關閉又無法對頁面進行其他操作,怎么辦呢?
解決方案
用鍵盤的Enter鍵來關閉該彈出框。
由於send_keys方法只能是針對元素來發送selenium的key值,而當前案例無法定位到該彈出框。
所以使用 PyKeyboad 來實現用python操作鍵盤
具體解決步驟
步驟1、想要使用PyKeyboard,需要先安裝:pywin32->pyHook->PyUserInput
(1) 安裝pywin32
安裝國外源的pywin32,會經常遇到因為超時導致安裝失敗。因此建議用國內源來安裝。
可通過cmd來安裝國內源的pywin32,指令如下:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pywin32
其中:https://pypi.tuna.tsinghua.edu.cn/simple是清華大學的鏡像文件地址。
也可選擇其他國內源,例如:
阿里雲:https://mirrors.aliyun.com/pypi/simple/
豆瓣:https://pypi.douban.com/simple/
(2) 如何安裝pyHook
從https://blog.csdn.net/dianmomanxue/article/details/95044676
下載對應版本的pyHook后,通過cmd進入到該pyHook的文件夾路徑后,輸入:
pip install pyHook1.5.1cp37cp37mwin_amd64.whl
(3) 如何安裝PyUserInput
通過cmd,輸入:
pip install PyUserInput
步驟2、py文件中導入PyKeyboard,並輸入Enter鍵:
1 #導入PyKeyboard 2 from pykeyboard import PyKeyboard 3 4 #實例化對象 5 k=PyKeyboard() 6 7 #按下Enter鍵 8 k.press_key(k.return_key) # 其中return_key就是Enter鍵
若需要按下其他鍵,可選中PyKeyboard后,按ctrl+b,查看 special_key_assignment函數下的屬性的說明。
本文最開頭截圖完整的處理代碼如下:
若還有其它解決方案,歡迎留言交流!