安裝相關依賴
pip install selenium
下載 phantomjs 對應平臺的文件【當然也可以使用非phantomjs的方式,請自行查詢,文末的github庫中有對應的文件,覺得官網下載慢的同學可以使用對應的文件】
相關代碼
#! python3
# coding=utf-8
# 作者博客 http://coderknock.com
# 中文爲方框的話需要安裝字體
# 在centos中執行:yum install bitmap-fonts bitmap-fonts-cjk
# 在ubuntu中執行:sudo apt-get install xfonts-wqy
# 如果要截取 html 文件需要使用 file:///D:/WebstormProjects/ZuiBlog/index.html 類似這樣的方式
from selenium import webdriver
import os
import time
import sys
url = sys.argv[1]
execName = 'phantomjs'
if os.name == 'nt':
execName = execName + '.exe'
driver = webdriver.PhantomJS(executable_path='./phantomjs/' + os.name + '/bin/' + execName)
# 設置寬高
driver.set_window_size(1280, 720)
# 這裏的executable_path填你phantomJS的路徑
driver.get(url)
time.sleep(2)
driver.save_screenshot("shot.png")
driver.quit()