반응형
우리의 친구, ChatGPT에게 물어봤습니다.
셀레늄은 다양한 프로그래밍 언어 (예: 자바, 파이썬, C# 등)를 지원하며, 브라우저를 직접 제어하여 사용자의 행동과 동일한 동작을 수행하게끔 만들어줍니다. 웹 페이지를 열거나 닫고, 버튼을 클릭하거나 텍스트를 입력하는 등의 작업을 자동화하여 테스트 케이스를 실행하거나 웹 데이터를 추출하는 데 사용됩니다.
크롤링을 하기 앞서 Selenium이 잘 작동하는지 확인하겠습니다.
Selenium 설치하기
- 작업 폴더에서 VS code를 실행하고 가상 환경으로 접속합니다.
source venv/Scripts/activate
- Selenium을 설치합니다.
pip install selenium
pip install webdriver-manager # 매번 업데이트 되는 크롬 드라이버를 적용시켜줌
Chrome driver 설치하기
- Chrome Driver는 Selenium과 함께 사용하며 구글 크롬 웹 브라우저를 제어합니다.
- 따라서 다음 url을 통해 접속하여 컴퓨터 사양에 맞는 Chrome Driver를 설치합니다.
https://googlechromelabs.github.io/chrome-for-testing/
Chrome for Testing availability
This page lists the latest available cross-platform Chrome for Testing versions and assets per Chrome release channel. Consult our JSON API endpoints if you’re looking to build automated scripts based on Chrome for Testing release data. Last updated @ 20
googlechromelabs.github.io
- 경로를 꼭 기억하세요!
- 이제 VS code의 terminal에 jupyter lab을 입력하여 주피터 랩을 실행합니다.
설치 확인하기
- Selenium 버전 확인을 합니다. 저는 4.11.2로 나오네요.
import selenium
print(selenium.__version__)
- Chrome Driver를 수동으로 설정합니다. path를 잘 입력해주세요! 저는 현재 폴더 안에 driver 폴더를 만들고 그 안에 다운받은 Chrome Driver파일들을 넣어놨습니다.
- 경로는 다음과 같이 확인합니다. >>> 다음에 입력된 건 저의 경로입니다.
import os
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * (level)
print('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
print('{}{}'.format(subindent, f))
list_files("driver")
>>>
driver/
chromedriver.exe
LICENSE.chromedriver
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
CHROME_DRIVER_PATH = './driver/chromedriver.exe'
service = Service(executable_path=CHROME_DRIVER_PATH)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
#크롬 드라이버에 url 주소 넣고 실행
driver.get('https://www.google.co.kr/')
time.sleep(3) # 페이지가 완전히 로딩되도록 3초동안 기다림
- 새로운 창으로 google이 보이면 성공입니다!
- 다음도 확인합니다.
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')
- 새로운 창으로 naver가 보이면 성공입니다!
드라이버 종료하기
- 사용을 다 한 후에는 다음을 입력하여 드라이버를 꼭 종료해줍니다. 이런 습관이 나의 컴퓨터의 램의 힘듦을 덜어줄 수 있습니다.
driver.quit()
감사합니다!
'Python > Crawling' 카테고리의 다른 글
[Crawling]_서울열린데이터광장에서 API로 데이터 수집하기 (0) | 2023.08.15 |
---|---|
[Crawling]_API를 이용하여 웹에서 정보 가져오기 (0) | 2023.08.07 |
[Crawling]_뉴스 타이틀만 가져올 수 있을까? (0) | 2023.08.06 |
[BeautifulSoup]_'아름다운 스프' 아니고 data를 가져오는 것? - find() (0) | 2023.08.06 |
[Crawling]_웹 페이지의 데이터를 가지고 올 수 있을까? (0) | 2023.08.04 |