How To Run Selenium With Chrome In Docker

前端 未结 4 1361
孤独总比滥情好
孤独总比滥情好 2021-01-31 04:56

I installed google-chrome in a Docker, but when I run my Python 2 script of Selenium, it failed like this:

automation@1c17781fef0c:/topology-editor/test$ python          


        
4条回答
  •  心在旅途
    2021-01-31 05:45

    The best way to use selenium in a docker container you need to do followings.

    Your need to add next lines to your Dockerfile

    # install google chrome
    RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
    RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'
    RUN apt-get -y update
    RUN apt-get install -y google-chrome-stable
    
    # install chromedriver
    RUN apt-get install -yqq unzip
    RUN wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip
    RUN unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/
    
    # set display port to avoid crash
    ENV DISPLAY=:99
    
    # install selenium
    RUN pip install selenium==3.8.0
    

    Then your code should be like this. Especially you need to declare your driver like below:

    from selenium import webdriver
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--window-size=1420,1080')
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(chrome_options=chrome_options)
    
    driver.get('www.google.com')
    screenshot = driver.save_screenshot('test.png')
    driver.quit()
    

提交回复
热议问题