[Ubuntu] 크롤링을 위한 selenium 사용

Taehong Jang·2023년 1월 26일
0
post-thumbnail

우분투 환경의 컨테이너에서 실행했음

selenium을 사용하려면 특정 브라우저와 그에 맞는 드라이버설치가 필요함.

chrome을 사용할 것임.

  • 우분투의 패키지들 업데이트
apt-get update
  • 크롬 설치
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

sudo apt install ./google-chrome-stable_current_amd64.deb #컨테이너라서 sudo 없이 실행했음

cf. wget이 없다면 설치해야함
의존성 문제가 발생하는 경우가 있는데, apt --fix-broken install 명령어 실행하라고 떠서 사용

  • 크롬 버전확인
google-chrome -version
  • 버전에 맞는 드라이버 설치
    그냥 검색창에 chromedriver라고 치면 다운 받는 사이트가 있음. 해당 사이트에 chrome 버전에 맞는 드라이버 파일에 대한 정보가 있다. 선택해서 들어가면

다음과 같이 뜬다. 내 환경에 맞는 linux64.zip에 해당되는 다운로드 파일을 우클릭해서 링크복사 해옴.

https://chromedriver.storage.googleapis.com/109.0.5414.74/chromedriver_linux64.zip

https://chromedriver.storage.googleapis.com/{설치할 버전}/{운영체제에 맞는 파일}.zip 형태이므로 상황에 맞게 쓰면 되겠다

wget https://chromedriver.storage.googleapis.com/109.0.5414.74/chromedriver_linux64.zip # 해당 파일 다운로드

unzip chromedriver_linux64.zip # 다운받은 파일 압축풀기

unzip하고 나면 chromedriver 파일이 있는데 해당 파일의 경로가 중요하다.

  • selenuim 사용하여 작동 확인
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")

# linux 환경에서 필요한 option
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
# excutable_path는 chromdriver가 위치한 경로를 적어주면 된다. code와 동일한 경로일 경우 아래처럼 'chromdriver' 만 적어주거나 아예 excutable_path 자체가 없어도 된다. 이해를 위해 써놓았을 뿐. 
# ex) driver = webdriver.Chrome(chrome_options=chrome_options)
driver = webdriver.Chrome(excutable_path ='chromedriver',chrome_options=chrome_options)

url = 'https://www.google.com'
driver.get(url)

처음에 chrome_options 없이 실행해보니깐 아래와 같은 에러가 나왔었다.
위에 chrome_options는 리눅스 환경이라면 전달하기.

"name": "WebDriverException",
"message": "Message: unknown error: Chrome failed to start: exited abnormally.\n (unknown error: DevToolsActivePort file doesn't exist)\n (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.

0개의 댓글