python3结合Headless Chrome网页截图

首先启动Headless Chrome

可以使用Docker 来启动

1
docker run -it --rm --name alpine-chrome -p 9222:9222 einverne/alpine-chrome

启动之后可以访问: http://localhost:9222/json 来查看是否启动成功。

安装pychrome模块

1
pip install -U pychrome

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import pychrome
import base64
def screenshot(browser, url, filename):
tab = browser.new_tab()
tab.start()
tab.call_method('Page.navigate', url=url, _timeout=5)
tab.wait(10)
screen_base64 = tab.call_method("Page.captureScreenshot")
image_data = screen_base64.get('data', '')
with open(filename, 'wb') as f:
f.write(base64.b64decode(image_data))
tab.stop()
browser.close_tab(tab)
if __name__ == '__main__':
browser = pychrome.Browser(url="http://127.0.0.1:9222")
screenshot(browser, 'http://baidu.com', 'filename.png')
Author: 1314mylove
Link: https://blog.1314mylove.com/2018/04/python3结合Headless Chrome网页截图/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.