Post

selenium을 공부해보자!

셀레니움 저장소

python 기본설정

 파이썬 가상환경 만들기

1
$ python -m venv 가상환경_이름

ctrl+shift+p 로 가상환경 잡아주기(안하면 다른 환경이랑 꼬이게 되어 불편하다.)

selenium 설치

1
$ pip install selenium

크롬 버전 확인

chrome version

webdriver 불러오기(크롬 버전 114 이하)

 selenium은 웹 드라이버를 켜서 실행 시키기에 webdriver가 필요하다. webdriver다운로드.

1
2
3
from selenium import webdriver

driver = webdriver.Chrome("webdriver경로")

webdriver 불러오기(크롬 버전 115 이상)

 115 버전 이상부터는 webdriver가 필요 없어졌다.

1
2
3
from selenium import webdriver

driver = webdriver.Chrome()

webdriver 실행

 웹드라이버를 실행할 url 주소를 이용한다.

1
2
3
4
5
from selenium import webdriver

driver = webdriver.Chrome()
url = "https://oil-ramp-cat.github.io"
driver.get(url)

웹 페이지 로딩 대기

 웹 페이지가 로딩되지도 않았는데 요소를 불러오려고 하면 요소를 찾을 수 없다는 경고와 함께 프로그램이 종료됩니다.  그것을 해결하기위해 대기시간을 줄 수 있죠. 그리고 그 방법에는 2가지가 있습니다.

1. sleep()

  이 코드는 파이썬에 내장되어있는 함수로 ()안에 초를 넣어주면 그 시간동안 대기합니다.

1
2
3
4
5
import time

second = 10
time.sleep(second) #10초 대기

2. implicitly_wait()

selenium에 내장되어있는 함수로 ()안에 초를 넣어주면 됩니다.

sleep()과의 차이점은 impliciyly_wait()은 ‘초’안에 웹페이지를 로딩했다면 ‘초’를 다 세지 않고 넘어가고, 아니라면 ‘초’동안 기다리게 됩니다.

1
2
3
4
5
from selenium import webdriver

second = "10"
driver = webdriver.Chrome()
driver.implicitly_wait(second)

요소 선택

 여기저기 찾아보다 보니 아무래도 시간이 지남에 따라 코드의 사용법이 달라졌나보군요.

과거
1
driver.find_element_by_요소종류()


조건에 일치하는 가장 첫번째 요소를 반환

1
2
3
from selenium.webdriver.common.by import By

driver.find_element(By.CSS_SELECTOR, "요소 위치")#css_selector 기준으로

조건에 일치하는 모든 요소를 list형태로 반환

1
2
3
4
from selenium.webdriver.common.by import By

image = driver.find_elements(By.CSS_SELECTOR, "요소들 위치")#css_selector 기준으로
#이미지 요소들을 가져온다고 했을 때 예시

By. 뒤에 올 수 있는 목록

CSS_SELECTOR
CLASS_NAME
ID
XPATH
NAME
LINK_TEXT
TAG_NAME
PARTIAL_LINK_TEXT

ChromeOptions()

그롬 웹 드라이버 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
options = webdriver.ChromeOptions()

user_agent = "설정 값"
options.add_argument('user-agent=' + user_agent)#설정한 user-agent로 변경
options.add_argument('headless')#headless모드, 브라우저가 뜨지 않고 코드에서만 실행
options.add_argument('--window-size= x, y')#브라우저 크기 x, y
options.add_argument('--start-maximized')#브라우저 최대화로 실행
options.add_argument('--start-fullscreen')#브라우저 풀스크린 모드로 실행
options.add_argument('--blink-settings=imagesEnabled=False')#브라우저 이미지 로딩 안함
options.add_argument('--mute-audio')#음속어
options.add_argument('incognito')#시크릿 모드
mobile_emulation = ("deviceName": "iphone SE")
options.add_experimental_option("mobileEmulation", mobile_emultaion)

execute_script

공부중!

추가기능

1. 페이지 내리기

1
2
3
4
5
def scroll_down(driver):
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")#함수설정
    time.sleep(1)#너무 빠르면 로딩 불가능

scroll_down(driver)#함수 사용
This post is licensed under CC BY 4.0 by the author.