所有方式截取的都是顶级窗口的的界面

调用windows API

import time
import win32gui, win32ui, win32con, win32api
def window_capture(filename):
  hwnd = 0 # 窗口的编号,0号表示当前活跃窗口
  # 根据窗口句柄获取窗口的设备上下文DC(Divice Context)
  hwndDC = win32gui.GetWindowDC(hwnd)
  # 根据窗口的DC获取mfcDC
  mfcDC = win32ui.CreateDCFromHandle(hwndDC)
  # mfcDC创建可兼容的DC
  saveDC = mfcDC.CreateCompatibleDC()
  # 创建bigmap准备保存图片
  saveBitMap = win32ui.CreateBitmap()
  # 获取监控器信息
  MoniterDev = win32api.EnumDisplayMonitors(None, None)
  w = MoniterDev[0][2][2]
  h = MoniterDev[0][2][3]
  # print w,h   #图片大小
  # 为bitmap开辟空间
  saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
  # 高度saveDC,将截图保存到saveBitmap中
  saveDC.SelectObject(saveBitMap)
  # 截取从左上角(0,0)长宽为(w,h)的图片
  saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
  saveBitMap.SaveBitmapFile(saveDC, filename)

ImageGrab

import time
from PIL import ImageGrab
#works on windows
img = ImageGrab.grab(bbox=(300, 300, 800, 800))# X1,Y1,X2,Y2
img.save("名字.png")

Selenium web截图

需要有浏览器相应的selenium驱动,驱动下载地址参见Selenium 官网

from selenium import webdriver
import time
def capture(url, filename="capture.png"):
  browser = webdriver.Chrome(r"chromedriver.exe")
  browser.set_window_size(1200, 900)
  browser.get(url) 
  browser.execute_script("""
  (function () {
   var y = 0;
   var step = 100;
   window.scroll(0, 0);
   function f() {
    if (y < document.body.scrollHeight) {
     y += step;
     window.scroll(0, y);
     setTimeout(f, 50);
    } else {
     window.scroll(0, 0);
     document.title += "scroll-done";
    }
   }
   setTimeout(f, 1000);
  })();
 """)
  for i in range(30):
    if "scroll-done" in browser.title:
      break
    time.sleep(1)
  browser.close()

PyQt5

from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import win32gui
import sys

hwnd = win32gui.FindWindow(None, 'C:\Windows\system32\cmd.exe')
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()

img = screen.grabWindow(hwnd).toImage()
img.save("screenshot.jpg")

pyscreenshot

import pyscreenshot

# works on windows,linux,mac
im = pyscreenshot.grab(bbox=(200, 200, 800, 800))  # X1,Y1,X2,Y2
im.save("screenshot.png")

pyautogui

import pyautogui 
img = pyautogui.screenshot(region=[100,100,600,600]) # x,y,w,h
img.save('screenshot.png')

本文链接:http://nix.pub/article/screenshot/