python截图

你不能把这个世界,让给你所鄙视的人。

简单的三行代码就可以实现:

1
2
3
from PIL import ImageGrab
pic = ImageGrab.grab()
pic.save('1.jpg')

使用 selenium

1
2
3
4
5
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://news.baidu.com/')
browser.save_screenshot('capture.png')
browser.close()

加载js,使网页显示完全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from selenium import webdriver
import time

def take_screenshot(url, save_fn="capture.png"):
browser = webdriver.Chrome() # Get local session of firefox
browser.set_window_size(1200, 900)
browser.get(url) # Load page
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, 100);
} else {
window.scroll(0, 0);
document.title += "scroll-done";
}
}

setTimeout(f, 1000);
})();
""")

for i in xrange(30):
if "scroll-done" in browser.title:
break
time.sleep(10)

browser.save_screenshot(save_fn)
browser.close()

if __name__ == "__main__":

take_screenshot("http://codingpy.com")

使用 PhantomJS(效果不太好)

1
2
3
4
5
from selenium import webdriver
br = webdriver.PhantomJS()
br.get('http://www.baidu.com')
br.save_screenshot('screenshot.png')
br.quit()

升级版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import StringIO
from selenium import webdriver
from PIL import Image

# Install instructions
#
# npm install phantomjs
# sudo apt-get install libjpeg-dev
# pip install selenium pillow


driver = webdriver.PhantomJS()
driver.set_window_size(1366, 728) # optional
driver.get('http://hassyon.com')
driver.save_screenshot('screen_hires.png')

screen = driver.get_screenshot_as_png()

# Crop it back to the window size (it may be taller)
box = (0, 0, 1366, 728)
im = Image.open(StringIO.StringIO(screen))
region = im.crop(box)
region.save('screen_lores.jpg', 'JPEG', optimize=True, quality=95)