Last active
February 5, 2023 03:07
-
-
Save Kazuki-tam/2d0394c6cbce9a3e7ac08cf92d406e29 to your computer and use it in GitHub Desktop.
colaboratory_screenshot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 日本語フォントインストール | |
!apt-get -y install fonts-ipafont-gothic | |
!apt-get -y install fonts-ipafont-mincho | |
# ライブラリインポート | |
from google.colab import files | |
import time | |
import shutil | |
import os | |
from selenium import webdriver | |
from selenium.webdriver.chrome.options import Options | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.support.ui import WebDriverWait | |
from selenium.webdriver.support import expected_conditions as EC | |
# Chromeヘッドレスモード起動 | |
options = webdriver.ChromeOptions() | |
options.headless = True | |
options.add_argument('--no-sandbox') | |
options.add_argument('--disable-dev-shm-usage') | |
driver = webdriver.Chrome('chromedriver',options=options) | |
driver.implicitly_wait(10) | |
# 対象URL | |
urls = ['https://example.com', 'https://example.com/about/'] | |
# ファイル名接頭辞 | |
fileNamePrefix = "screen" | |
# ウインドウ幅指定 | |
# 初期値: False, スマホ: 375 | |
# windowSizeWidth = False | |
windowSizeWidth = 1200 | |
# ウインドウ高さ指定 | |
# 初期値: False | |
windowSizeHeight = False | |
# windowSizeHeight = 1000 | |
# 連番初期値 | |
shotNum = 0 | |
# ダウンロードフォルダ作成 | |
folderCheck = os.path.exists('screen-shot') | |
if folderCheck: | |
shutil.rmtree('screen-shot') | |
os.mkdir('screen-shot') | |
# 繰り返し処理 | |
for url in urls: | |
# パス指定 | |
folderPath = 'screen-shot/' + fileNamePrefix + '-' + str(windowSizeWidth) + '-' if windowSizeWidth else 'screen-shot/' + fileNamePrefix + '-' | |
# サイトURL取得 | |
driver.get(url) | |
WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located) | |
# ウインドウ幅・高さ指定 | |
windowWidth = windowSizeWidth if windowSizeWidth else driver.execute_script('return document.body.scrollWidth;') | |
windowHeight = windowSizeHeight if windowSizeHeight else driver.execute_script('return document.body.scrollHeight;') | |
driver.set_window_size(windowWidth, windowHeight) | |
# スクロール処理 | |
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') | |
# 処理後一時待機 | |
time.sleep(3) | |
# ファイル連番追加 | |
shotNum += 1 | |
shotNumStringified = str(shotNum) | |
# スクリーンショット格納 | |
driver.save_screenshot(folderPath + shotNumStringified + '.png') | |
# サーバー負荷軽減処理 | |
time.sleep(1) | |
# ブラウザ稼働終了 | |
driver.quit() | |
# zipファイル変換ダウンロード | |
!zip -r download.zip screen-shot | |
files.download('download.zip') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment