티스토리 뷰
728x90
Selenium
개요
- 웹 앱을 테스트하는 데 사용하는 프레임워크
- WebDriver라는 API를 이용해서 운영체제에 설치된 브라우저를 제어하는 프레임워크
- 크롤링을 할 때 JavaScript를 이용해서 비동기적으로 가져오는 데이터를 읽고자 할 때 이용 가능. 로그인 후 가져와야 하는 데이터를 불러올 때도 사용
- 메뉴얼
The Selenium Browser Automation Project
Selenium automates browsers. That's it!
www.selenium.dev
설치
pip install selenium
브라우저의 드라이버가 필요
크롬 드라이버
ChromeDriver - WebDriver for Chrome - Downloads
Current Releases If you are using Chrome version 115 or newer, please consult the Chrome for Testing availability dashboard. This page provides convenient JSON endpoints for specific ChromeDriver version downloading. For older versions of Chrome, please se
chromedriver.chromium.org
기본 API
- 접속: get(url)
- html 코드 읽어오기: page_source
- 일정 시간 대기: implicitly_wait(시간)
- 브라우저 종료: quit()
element 접근
하나만 찾는 API
find_element_by_name(이름)
find_element_by_id(아이디)
find_element_by_xpath(xpath)
배열로 찾는 API
find_element_by_css_selector(선택자)
find_element_by_css_class_name(클래스 이름)
find_element_by_css_name(태그)
element 동작 API
# 값이 입력됨
sends_keys(값)
# 클릭
click(), submit()
스크립트 실행
execute_script(스크립트 코드)
실습(다음 카카오 계정으로 로그인)
다음 카카오 로그인
카카오계정
accounts.kakao.com
선택자 확인
요소 선택 -> 마우스 오른쪽 -> 검사 -> 요소 HTML 우클릭 -> 복사 -> Xpath
코드
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
# 드라이버 경로 설정
os.environ['webdriver.chrome.driver'] = 'C:\\Users\\USER\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver'
driver = webdriver.Chrome()
#사이트 접속
driver.get("https://accounts.kakao.com/login/?continue=https%3A%2F%2Flogins.daum.net%2Faccounts%2Fksso.do%3Frescue%3Dtrue%26url%3Dhttps%253A%252F%252Fwww.daum.net#login")
# 5초간 대기
driver.implicitly_wait(5)
# 로그인 아이디, 비밀번호 입력
user_id = input("아이디")
password = input("비밀번호")
driver.find_element(By.XPATH,'//*[@id="loginId--1"]').send_keys(user_id)
driver.find_element(By.XPATH,'//*[@id="password--2"]').send_keys(password)
driver.find_element(By.XPATH,'//*[@id="mainContent"]/div/div/form/div[4]/button[1]').click()
while(True):
pass
capture가 발생하는 것을 확인할 수 있다. 자바스크립트를 이용해서 로그인하면 해결 가능하다.
네이버 로그인(자바스크립트 이용ㅅ)
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
# 드라이버 경로 설정
os.environ['webdriver.chrome.driver'] = 'C:\\Users\\USER\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver'
driver = webdriver.Chrome()
#사이트 접속
driver.get("https://nid.naver.com/nidlogin.login")
# 5초간 대기
driver.implicitly_wait(5)
# 로그인 아이디, 비밀번호 입력
user_id = input("아이디")
password = input("비밀번호")
driver.execute_script("document.getElementsByName('id')[0].value = \'"+user_id+"\'")
driver.execute_script("document.getElementsByName('pw')[0].value = \'"+password+"\'")
driver.find_element(By.XPATH,'//*[@id="log.login"]').click()
while(True):
pass
스크롤(자바스크립트 수행)을 하면서 데이터를 수집
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import os
# 드라이버 경로 설정
os.environ['webdriver.chrome.driver'] = 'C:\\Users\\USER\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver'
driver = webdriver.Chrome()
#사이트 접속
driver.get("https://www.youtube.com/results?search_query=%EB%89%B4%EC%A7%84%EC%8A%A4")
# 5초간 대기
driver.implicitly_wait(5)
i = 0
# 자동 스크롤
body = driver.find_element(By.TAG_NAME,'body')
while i < 10:
body.send_keys(Keys.PAGE_DOWN)
time.sleep(2)
i = i+1
while(True):
pass
728x90
'python' 카테고리의 다른 글
[python, DataFrame]데이터 탐색 (1) | 2024.02.13 |
---|---|
[python, DataFrame]Mysql의 데이터로 Data Frame 형성 (0) | 2024.02.13 |
[python] 데이터 수집 (1) | 2024.02.13 |
[python] numpy(2) (1) | 2024.02.13 |
[python] numpy(1) (0) | 2024.02.13 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 티스토리챌린지
- 웹
- 프로그래머스
- 웹프로그래밍
- SSAFYcial
- 전자회로
- 위니브
- PANDAS
- 알고리즘이론
- 백준
- 인프런
- ssafy기자단
- 알고리즘
- 백준알고리즘
- numpy
- it도서큐레이션
- Python
- 코딩테스트
- 생성형 AI
- django
- SSAFY
- dataframe
- 웹개발
- 더오름
- 위니브엠베서더
- 인프런강의
- 제주코딩베이스캠프
- 파이썬
- 인프런강의후기
- 오블완
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함
250x250