Python3+Selenium으로 웹사이트 스크린샷 촬영

실행에 필요한 모듈 설치



Selenium 설치


#Windowsの場合
pip install selenium
#Macの場合
pip3 install selenium

ChromeDriver 설치 및 PATH를 통과하는 방법



WEB에 게재된 Selenium을 사용한 프로그램이 오류를 토한다면,
소스 코드 문제보다는이 ChromeDriver를 설치할 수 없거나
PATH가 다니지 않았기 때문에 아래와 같은 에러가 나온다고 하는 것이 많은 것이 아닐까? 라고 생각합니다
Traceback (most recent call last):
  File "c:/Users/User/Desktop/sample.py", line 7, in <module>
    driver = webdriver.Chrome(options=options)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.
    Please see https://sites.google.com/a/chromium.org/chromedriver/home

상기 에러에 대한 대책은 사조에서는 3가지 있습니다.
  • ChromeDriver를 설치 한 후 경로를 통과합니다.
  • webdriver.Chrome () 설명에 경로를 직접 치십시오.
  • import를 추가하고 경로를 통과

  • 추천은 첫 번째 ChromeDriver를 설치 한 다음 경로를 통과합니다.
    이 기사에서는 제목 내용의 설명으로 빨리 이동하고 싶기 때문에,
    가장 쉽게 대응할 수 있는 세 번째 import를 추가하여 패스를 통과하는 방법을 소개합니다.
    다른 방법으로 대책하고 싶은 분은 Windows인지 Mac인지에 따라 방법이 다르기 때문에
    ChromeDriver와 OS 키워드로 검색해 보세요.

    import를 추가하고 경로를 통과하는 방법



    ChromeDriver 설치


    #Windowsの場合
    pip install chromedriver-binary
    #Macの場合
    pip3 install chromedriver-binary
    

    import 설명


    import chromedriver_binary
    

    소스 코드



    아래 소스 코드 내에는 import를 추가하고 패스를 통과하는 방법으로 소개했다
    import의 기술은 없기 때문에 필요하면 추기해 실행해 주세요.
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    url = 'https://www.oanda.jp/lab-education/oanda_lab/oanda_rab/currency_power_balance/'
    options = Options()
    options.add_argument('--headless')
    driver = webdriver.Chrome(options=options)
    driver.get(url)
    
    page_width = driver.execute_script('return document.body.scrollWidth')
    page_height = driver.execute_script('return document.body.scrollHeight')
    print('page_width', page_width, sep=':')
    print('page_height', page_height, sep=':')
    driver.set_window_size(page_width, page_height)
    
    driver.save_screenshot('screenshot.png')
    driver.close()
    driver.quit()
    exit()
    

    오류가 발생하면



    Selenium을 설치했습니다. ChromeDriver도 설치했다. import도 썼다.
    그렇지만 에러가 되었다고 하는 경우, 아래와 같은 에러가 발생했을 경우의 대처를 추기해 둡니다.
    DevTools listening on ws://127.0.0.1:62988/devtools/browser/a9ef2367-49e5-4405-b33f-2782f0eaad42
    Traceback (most recent call last):
      File "sample.py", line 9, in <module>
        driver = webdriver.Chrome(options=options)
      File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 76, in __init__
        RemoteWebDriver.__init__(
      File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in 
    __init__
      File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in 
    start_session
        response = self.execute(Command.NEW_SESSION, parameters)
      File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in 
    execute
        self.error_handler.check_response(response)
      File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242,
        in check_response
        raise exception_class(message, screen, stacktrace)
    selenium.common.exceptions.SessionNotCreatedException:
        Message: session not created: This version of ChromeDriver only supports Chrome version 84
    

    이 오류는 오류 메시지 내에 ChromeDriver 버전이 84가 아니면 지원하지 않는다고 쓰고 있습니다.
    실제로 설치된 Chrome 버전과 ChromeDriver 불일치로 인해 발생하는 오류입니다.

    지금 설치된 Chrome 브라우저 버전을 확인하고,
    설치하는 ChromeDriver를 Chrome 브라우저 버전과 동일하거나 이전 버전으로 설정하여 개선합니다.

    Chrome 브라우저 설정 > 도움말 > Google Chrome 정보를 눌러 Chrome 브라우저 버전을 확인할 수 있습니다.

    화면에서는 버전이 83.0.4103.116이므로 설치 명령에 버전을 추가하여 실행합니다.
    # Windowsの場合
    pip install chromedriver-binary==83.0.4103.116
    # Macの場合
    pip3 install chromedriver-binary==83.0.4103.116
    

    일치하는 버전의 ChromeDriver가 있으면 대상 버전의 ChromeDriver가 설치되어 완료되었지만
    일치하는 버전의 ChromeDriver가 없는 경우 다음과 유사한 오류 메시지가 표시됩니다.
    Collecting chromedriver-binary==83.0.4103.116
      ERROR: Could not find a version that satisfies the requirement chromedriver-binary==83.0.4103.116
      (from versions: 2.29.1, 2.31.1, 2.33.1, 2.34.0, 2.35.0, 2.35.1, 2.36.0, 2.37.0, 2.38.0,
                      2.39.0, 2.40.1, 2.41.0, 2.42.0, 2.43.0, 2.44.0, 2.45.0, 2.46.0, 70.0.3538.16.0,
                      70.0.3538.67.0, 70.0.3538.97.0, 71.0.3578.30.0, 71.0.3578.33.0, 71.0.3578.80.0,
                      71.0.3578.137.0, 72.0.3626.7.0, 72.0.3626.69.0, 73.0.3683.20.0, 73.0.3683.68.0, 
                      74.0.3729.6.0, 75.0.3770.8.0, 75.0.3770.90.0, 75.0.3770.140.0, 76.0.3809.12.0,
                      76.0.3809.25.0, 76.0.3809.68.0, 76.0.3809.126.0, 77.0.3865.10.0, 77.0.3865.40.0,
                      78.0.3904.11.0, 78.0.3904.70.0, 78.0.3904.105.0, 79.0.3945.16.0, 79.0.3945.36.0,
                      80.0.3987.16.0, 80.0.3987.106.0, 81.0.4044.20.0, 81.0.4044.69.0, 81.0.4044.138.0,
                      83.0.4103.14.0, 83.0.4103.39.0, 84.0.4147.30.0)
    ERROR: No matching distribution found for chromedriver-binary==83.0.4103.116
    

    설치할 ChromeDriver를 Chrome 브라우저 버전 이전 버전으로 변경하면
    위에서 설명했으므로이 목록에서 이전 버전이 될 것입니다.

    83.0.4103.39.0

    위 버전이 이전 버전에 해당하므로 이 버전의 ChromeDriver를 설치합니다.
    # Windowsの場合
    pip install chromedriver-binary==83.0.4103.39.0
    # Macの場合
    pip3 install chromedriver-binary==83.0.4103.39.0
    

    설치가 완료되면 스크린샷을 다시 찍는 프로그램을 실행해 보면
    PS C:\Users\User\Desktop> python sample.py
    
    DevTools listening on ws://127.0.0.1:63400/devtools/browser/70375409-a059-4976-b851-176545080407
    page_width:912
    page_height:1963
    

    이러한 메시지가 표시되고 실행한 위치에 screenshot.png 가 출력되고 있을 것입니다.

    좋은 웹페이지 즐겨찾기