본문 바로가기

python

[python]selenium을 이용한 스크린샷

첫 페이지부터 중간까지 캡쳐

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

def capture_full_page_screenshot(url, output_path, number):
    chrome_options = Options()
    chrome_options.add_argument('--headless')  # 브라우저를 화면에 띄우지 않고 실행합니다.
    driver = webdriver.Chrome(options=chrome_options)

    try:
        for num in range(1, number + 1):
            # Construct the URL with the current number
            current_url = f"{url}&number={num}"
            driver.get(current_url)
            # Wait for the page to load completely (you might need to adjust the wait time)
            driver.implicitly_wait(10)

            # Set window size to capture the entire page
            driver.set_window_size(1900, 3500)

            # Capture the screenshot
            current_output_path = f"{num}_a.png"
            driver.save_screenshot(current_output_path)
            print(f"Screenshot {current_output_path} captured and saved.")

    finally:
        driver.quit()

# Example usage
url = "http://localhost:8080/test/readcsv?"
number_of_pages = 1000
capture_full_page_screenshot(url, "output_folder/", number_of_pages)

 

 

페이지의 중간부터 마지막까지 캡쳐하는 코드

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def capture_full_page_screenshot(url, output_path, number):
    chrome_options = Options()
    chrome_options.add_argument('--headless')  # 브라우저를 화면에 띄우지 않고 실행합니다.
    driver = webdriver.Chrome(options=chrome_options)

    try:
        for num in range(1, number + 1):
            # Construct the URL with the current number
            current_url = f"{url}&number={num}"
            driver.get(current_url)
            # Wait for the page to load completely (you might need to adjust the wait time)
            driver.implicitly_wait(10)

            driver.execute_script("window.scrollTo(0, 3500)")
            time.sleep(1)  # Wait for the page to scroll

            # Set window size to capture the entire page
            driver.set_window_size(1900, 3500)

            # Capture the screenshot
            current_output_path = f"{num}_b.png"
            driver.save_screenshot(current_output_path)
            print(f"Screenshot {current_output_path} captured and saved.")

    finally:
        driver.quit()

# Example usage
url = "http://localhost:8080/test/readcsv?"
number_of_pages = 1000
capture_full_page_screenshot(url, "output_folder/", number_of_pages)

 

페이지 길이를 체크 후 캡쳐를 하려고 하니 오류가 떠서 길이를 7000으로 수정

 

'python' 카테고리의 다른 글

python time out error  (0) 2022.02.17
점프투 플라스크 오류  (0) 2022.01.17