對網頁進行爬取並另存時,遇到一個問題:selenium中鍵盤或是鼠標的操作都是以網頁內的某個元素為對象,當遇到windows窗體時就無法繼續操作,如下圖。
我想點擊另存為,並輸入路徑再點擊保存按鈕.....
這時就可用到pywin32這個包了,用來模擬鍵盤輸入或鼠標點擊。
下載地址:
https://sourceforge.net/projects/pywin32/files/pywin32/
根據自己python版本找對應的安裝包...
好了,可以開始操作了:
# coding=utf-8
from selenium import webdriver
import win32api
import win32con
import win32clipboard
from ctypes import *
import time
# 瀏覽器打開百度網頁
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("https://www.baidu.com/")
time.sleep(2)
# 獲取頁面title作為文件名
title = browser.title
# 設置路徑為:當前項目的絕對路徑+文件名
path = (os.path.dirname(os.path.realpath(__file__)) + "\\" + title + ".html")
# 將路徑復制到剪切板
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(path)
win32clipboard.CloseClipboard()
# 按下ctrl+s
win32api.keybd_event(0x11, 0, 0, 0)
win32api.keybd_event(0x53, 0, 0, 0)
win32api.keybd_event(0x53, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(0x11, 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)
# 鼠標定位輸入框並點擊
windll.user32.SetCursorPos(700, 510)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
time.sleep(1)
# 按下ctrl+a
win32api.keybd_event(0x11, 0, 0, 0)
win32api.keybd_event(0x41, 0, 0, 0)
win32api.keybd_event(0x41, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(0x11, 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)
# 按下ctrl+v
win32api.keybd_event(0x11, 0, 0, 0)
win32api.keybd_event(0x56, 0, 0, 0)
win32api.keybd_event(0x56, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(0x11, 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)
# 按下回車
win32api.keybd_event(0x0D, 0, 0, 0)
win32api.keybd_event(0x0D, 0, win32con.KEYEVENTF_KEYUP, 0)
browser.close()
有個小問題...鼠標定位
windll.user32.SetCursorPos(700, 510)
可能因為屏幕大小的不同而參數不同,待我多學點了再來更正~