基于Python+Selenium實現網頁進行自動截圖
Selenium是一個用來進行自動化測試的工具,他可以調用正常的瀏覽器進行一系列的操作。
1、安裝Selenium
直接命令行下執行 pip install Selenium 即可,方便簡單。
2、下載Chrome Driver
下載地址為:http://code.google.com/p/chromedriver/downloads/list
下載完畢后將下載到的chromedriver.exe 放在 system32目錄行下或與你的程序放在同一個目錄。
3、編寫截圖的Python代碼
具體代碼如下:
# -*- coding: utf-8 -*-
from selenium import webdriver
import time
def capture(url, save_fn="capture.png"):
browser = webdriver.Chrome()
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 xrange(30):
if "scroll-done" in browser.title:
break
time.sleep(1)
browser.save_screenshot(save_fn)
browser.close()
if __name__ == "__main__":
capture("http://www.baidu.com")引用地址:http://www.biaodianfu.com/python-selenium-capture.html
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!