pywin32 + PyQt5
需要先 pip 安装 pywin32、PyQt5 ,相关依赖 pip 会自动安装。
pip install pywin32
pip install PyQt5
下面这种方式比较强悍,可以根据活跃窗口的 title 名称,自动找到对应的窗口然后进行截图。
import sysimport win32gui
from PyQt5.QtWidgets import QApplicationclass Window(object):def __init__(self, hwnd):self.hwnd = hwndself.window_title = win32gui.GetWindowText(hwnd)self.window_class_name = win32gui.GetClassName(hwnd)self.window_rect = win32gui.GetWindowRect(hwnd)def __str__(self):return f"hwnd: {self.hwnd}, window_title: {self.window_title}, window_class_name: {self.window_class_name}, window_rect: {self.window_rect}"class WindowsHandler(object):def __init__(self):self.current_windows = []self._init_all_windows()def _init_all_windows(self):win32gui.EnumWindows(self._get_window, 0)def _get_window(self, hwnd, nouse):if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):self.current_windows.append(Window(hwnd))def get_windows_by_title(self, title_name):return [window for window in self.current_windows if title_name in window.window_title]def screenshot_window_byPyQt(self, window: Window, img_save_path):app = QApplication(sys.argv)screen = QApplication.primaryScreen()img = screen.grabWindow(window.hwnd).toImage()img.save(img_save_path)if __name__ == '__main__':wh = WindowsHandler()windows = wh.get_windows_by_title("Looooking")if windows:window = windows[0]print(window)wh.screenshot_window_byPyQt(window, "./test.png")
pyautogui
安装好 pyautogui 库就好了,这个库主要用于鼠标键盘模拟操作,当然屏幕截图也是手到擒来。
import pyautoguiif __name__ == '__main__':screenshot = pyautogui.screenshot() # 截全屏screenshot.save("full.png")screenshot = pyautogui.screenshot(region=(100, 100, 500, 500)) # 截图指定区域部分screenshot.save("part.png")
selenium
chromedriver(114 及以前的旧版): CNPM Binaries Mirror
chromedriver (115 及之后的新版):百度网盘链接:https://pan.baidu.com/s/1yk6js4yz_NBzXAp71ZIOzA?pwd=2vo3提取码:2vo3
还可以使用 selenium 对打开的浏览器窗口截图。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ECif __name__ == '__main__':options = webdriver.ChromeOptions()service = webdriver.ChromeService(executable_path=r"./driver/chromedriver.exe")driver = webdriver.Chrome(options=options, service=service)driver.implicitly_wait(3)driver.maximize_window()driver.get('https://www.baidu.com/s')xpath_input = '//*[@id="kw"]' # 搜索框xpath_search = '//*[@id="su"]' # 搜索按钮ele_input = driver.find_element(By.XPATH, xpath_input)ele_input.clear()ele_input.send_keys("百度")driver.find_element(By.XPATH, xpath_search).click()WebDriverWait(driver, 3).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="page"]/div/strong/span')))driver.save_screenshot("./test.png")driver.quit()