Selenium은 간단하게 일회성으로 웹크롤링하기 좋은 패키지이다.
(다회성이 아닌 이유: 코드 유지-보수가 힘들기 때문)
이번 시간에는 Webdriver manager와 Selenium을 활용해 웹사이트에 접속하는 것을 해보자.
1. 환경 세팅
빈 폴더 생성 후 VS Code로 접속 -> 터미널 실행 후
$ virtualenv venv
Python 가상환경 설정
$ venv/Scripts/activate
가상환경 활성화
selenium
webdriver-manager
jupyterlab
$ pip install -r requirements.txt
requirements.txt 불러와서 pip로 설치
$ jupyter lab
jupyter lab 실행
python > crawling 폴더생성 후 test.ipynb 생성
2. 코드 작성 및 실행
import selenium
print(selenium.__version__)
코드 실행 당시 필자의 Selenium 버전은 4.11.0 이다.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get('https://www.naver.com')
위 코드 작성 후 실행
실행 결과: Selenium으로 Chrome 브라우저를 열어 네이버 페이지 로딩
3. 드라이버 종료
driver.quit()
드라이버 세션 종료 (그냥 닫기로 끄면 백그라운드에서 계속 돌아간다. 확실히 코드로 종료시키자!)
'# Coding > Web Crawling' 카테고리의 다른 글
Web Crawling (with Scrapy) (0) | 2023.08.21 |
---|---|
Web Crawling (with BeautifulSoup) (0) | 2023.08.21 |
Web Crawling (with Selenium) (2) (0) | 2023.08.21 |