일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- file
- pytorch
- Flask
- Converting
- PostgreSQL
- Database
- Python
- pandas
- DB
- enV
- CUDA
- docker
- Linux
- KAKAO
- LLM
- GitLab
- numpy
- git
- Container
- Laravel
- format
- Windows
- Package
- judge
- Mac
- Paper
- evaluation
- list
- TORCH
- AI
Archives
- Today
- Total
Daily Develope
[WEB] 동적 웹페이지 처리 with Python 본문
설치
pip install selenium
pip install bs4
사용 예시
일반적인 사용
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
# init.
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) # load chrome webdriver
driver.set_window_size(1200, 900)
driver.set_window_position(0, 0)
driver.get("https://my-daynamic-webpage.com")
driver.implicitly_wait(10) # 페이지 로딩까지 최대 10초 대기
# get data
my_btn = driver.find_element(By.XPATH, '//button[text()="my_buitton"]') # 특정 button 선택
my_btn.click() # 선택 버튼 클릭
- 스크롤 내리는 방법은 아래 Ref의 zenrows 페이지 참고
- xpath 사용법은 링크페이지 참고
웹페이지 스냅샷 저장
from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.common import exceptions
import time
if __name__ == "__main__":
options = wd.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument('--save-page-as-mhtml')
webdriver = wd.Chrome(options=options)
webdriver.get('https://target.webpage.url')
# 타겟페이지 정보 불러오기 및 저장
try:
webdriver.get("target_page_url")
webdriver.implicitly_wait(2)
res = webdriver.execute_cdp_cmd('Page.captureSnapshot', {})
with open(f"./downloads/target_file_name.mhtml", "w", encoding="utf-8") as f:
f.write(res['data'])
print(f"변환 완료")
except Exception as ex:
print(f"[ERROR]변환 실패")
기능
마우스 클릭
webdriver.find_element(By.XPATH, '//*[@id="loginForm_id"]').click()
텍스트 입력
webdriver.find_element(By.XPATH, '//*[@id="loginForm_id"]').send_keys("my_id")
Tab 전환
# 0번 Tab에서 1번 Tab으로 전환 (Focusing)
webdriver.switch_to.window(webdriver.window_handles[1])
로딩 대기
# 10초간 대기
webdriver.implicitly_wait(10)
작업종료 후 브라우저 대기
# 드라이버 생성 과정에 옵션 정의
from selenium import webdriver as wd
options = wd.ChromeOptions()
options.add_experimental_option("detach", True)
webdriver = wd.Chrome(options=options)
Logging
from selenium import webdriver as wd
options = wd.ChromeOptions()
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
service = wd.ChromeService(service_args=['--log-level=DEBUG'], log_output="./logs/log_test.log")
webdriver = wd.Chrome(options=options, service=service)
# cmd 출력 또는 앞서 설정한 경로에서 로그 확인
for per in webdriver.get_log("performance"):
print(per)
보안모듈 우회방법
(아래는 MAC 환경에서의 예시로 설명)
- Chrmoe 원격 디버거 실행
CMD 또는 Terminal에서 디버거 옵션과 함께 Chrome 실행
$ cd /Applications/Google Chrome.app/Contents/MacOS
$ ./Google\ Chrome.exe --remote-debugging-port=9222
- Chrome 디버거 연결
from selenium import webdriver as wd
options = wd.ChromeOptions()
# debugger 옵션과 충돌되지 않도록 옵션 설정 (예시_ detatch 옵션의 경우 충돌)
options.add_experimental_option("binary", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome.exe")
options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
webdriver = wd.Chrome(options=options)
- 기존 traverse 수행
Ref.
'Develope > Web' 카테고리의 다른 글
[CSS] 작성 규칙 (0) | 2024.05.02 |
---|---|
[SSL] NginX SSL 인증서 설정 (0) | 2023.08.17 |
[Web] XPath 간단 정리 (0) | 2023.05.09 |
[Web] curl & program code 변환 (관련링크) (0) | 2023.03.27 |
[Web] Multipart/form-data 요청(Request) in Python (0) | 2023.03.27 |
Comments