[Python] 웹 자동화 기초 - 경고창 이동, 쿠키, 자바스크립트 코드 실행

2022. 9. 29. 11:09·python/자동화
728x90
반응형

경고창 (alert)

경고창이 떴을 때 수락 또는 거절을 눌러주거나 경고창의 텍스트를 가져올 수 있다.

경고창 이동

#경고창으로 이동
driver.switch_to.alert

경고창 수락 / 거절

from selenium.webdriver.common.alert import Alert

Alert(driver).accept()    #경고창 수락 누름
Alert(driver).dismiss()   #경고창 거절 누름
print(Alert(driver).text  # 경고창 텍스트 얻음

쿠키 값 얻기

#쿠키값 얻기
driver.get_cookies()

#쿠키 추가
driver.add_cookie()

#쿠키 전부 삭제
driver.delete_all_cookies()

#특정 쿠기 삭제
driver.delete_cookie(cookiename)

자바스크립트 코드 실행

자바스크립트를 실행할 수 있다. 자주 그리고 많이 사용하는 자바스크립트 몇개를 알아본다.

스크롤 이동

#브라우저 스크롤 최하단으로 이동
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')

# CSS 셀렉터로 클릭
driver.execute_script("document.querySelector('body >  div.modal-options__buttons > button.btn.btn-primary').click();")

#또는
elemToclick = driver.~~~
driver.execute_script('arguments[0].click();', elemToclick)

# driver.find_element_by_css_selector(~~).click() 과 동일하나 이 코드가 작동하지 않을시 자바스크립트 코드를 시도해볼만하다.

# 스크롤 특정 엘리먼트로 이동
element = driver.find_element_by_css_selector('div > a')
driver.execute_script('arguments[0].scrollIntoView(true);', element)

새 탭 열기

# Opens a new tab and switches to new tab
driver.switch_to.new_window('tab')

    # Opens a new window and switches to new window
driver.switch_to.new_window('window')

스크린샷

#캡쳐할 엘레먼트 지정
element = driver.driver.find_element_by_class_name('ico.search_submit')
#캡쳐
element.save_screenshot('image.png')

뒤로가기 앞으로가기

# 뒤로가기
driver.back()

#앞으로 가기
driver.forward()

예외처리 – Exceptions

from selenium.common.exceptions import NoAlertPresentException, NoSuchElementException, TimeoutException, ElementNotInteractableException,NoSuchWindowException, NoSuchFrameException

# NoAlertPresentException 경고창 관련 명령어를 실행했으나 현재 경고창이 뜨지 않음
# NoSuchElementException 엘레먼트 접근하였으나 없음
# TimeoutException 특정한 액션을 실행하였으나 시간이 오래 지나도록 소식이 없음
# ElementNotInteractableException 엘리먼트에 클릭등을 하였으나 클릭할 성질의 엘리먼트가 아님
# NoSuchWindowException 해당 윈도우 없음
# NoSuchFrameException 해당 프레임 없음

shadow DOM 처리

#shadow dom 엘레먼트 열어주는법
element = driver.execute_script("return document.querySelector('#syndi_powerpage > div').shadowRoot").get_attribute('innerHTML') # css Selector 이용 # element 의 HTML 내용 return
# shadow dom 처리를 통한 크롬 인터넷 기록 삭제

def expand_shadow_element(element):
    shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
    return shadow_root

driver.get('chrome://settings/clearBrowserData')

elem = driver.find_element_by_css_selector('body > settings-ui')
elem1 = expand_shadow_element(elem)
elem1 = elem1.find_element_by_id('main')
elem2 = expand_shadow_element(elem1)
elem2 = elem2.find_element_by_tag_name('settings-basic-page')
elem3 = expand_shadow_element(elem2)
elem3 = elem3.find_element_by_tag_name('settings-privacy-page')
elem4 = expand_shadow_element(elem3)
elem4 = elem4.find_element_by_tag_name('settings-clear-browsing-data-dialog')
elem5 = expand_shadow_element(elem4)
elem5forconfirmelem = expand_shadow_element(elem4) # 인터넷 사용기록 삭제버튼 클릭을 위한 엘레먼트 따로 빼놓기
elem5 = elem5.find_element_by_id('clearFromBasic')
elem6 = expand_shadow_element(elem5)
elem6 = elem6.find_element_by_id('dropdownMenu')
elem6.find_element_by_css_selector('option[value="4"]').click() # 전체기간 선택
elem5forconfirmelem.find_element_by_id('clearBrowsingDataConfirm').click() # 인터넷 사용기록 삭제버튼 클릭

XHR 데이터 확인

from selenium.webdriver import DesiredCapabilities
import json

capabilities = DesiredCapabilities.CHROME
capabilities["goog:loggingPrefs"] = {"performance": "ALL"}  # newer: goog:loggingPrefs

try:
    s = Service(f'./{chrome_ver}/chromedriver.exe')
    driver = webdriver.Chrome(service=s, options=option, desired_capabilities=capabilities)
except:
    chromedriver_autoinstaller.install(True)
    s = Service(f'./{chrome_ver}/chromedriver.exe')
    driver = webdriver.Chrome(service=s, options=option, desired_capabilities=capabilities)
driver.implicitly_wait(7)

driver.get('blablablabla~~~')

logs_raw = driver.get_log("performance")
logs = [json.loads(lr["message"])["message"] for lr in logs_raw]

def log_filter(log_):
    return (
        # is an actual response
        log_["method"] == "Network.responseReceived"
        # and json
        and "json" in log_["params"]["response"]["mimeType"]
    )

for log in filter(log_filter, logs):
    request_id = log["params"]["requestId"]
    resp_url = log["params"]["response"]["url"]
    print(f"Caught {resp_url}")
    print(driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id}))

 

728x90
반응형

'python > 자동화' 카테고리의 다른 글

[Python] 웹크롤링 - 태그를 이용해서 크롤링하기 - (2) 사전구축  (0) 2023.03.07
[Python] 네이버 뉴스 기사 태그 출력하기  (0) 2022.09.29
[Python] 웹 자동화 기초 - 엘레먼트(클릭, 텍스트, 프레임 이동)  (0) 2022.09.29
[Python] 웹 자동화 기초 - 브라우저 열기, 닫기, 탭 이동  (0) 2022.09.29
[Python] 네이버 뉴스 기사 웹 크롤링 - 매크로  (0) 2022.09.28
'python/자동화' 카테고리의 다른 글
  • [Python] 웹크롤링 - 태그를 이용해서 크롤링하기 - (2) 사전구축
  • [Python] 네이버 뉴스 기사 태그 출력하기
  • [Python] 웹 자동화 기초 - 엘레먼트(클릭, 텍스트, 프레임 이동)
  • [Python] 웹 자동화 기초 - 브라우저 열기, 닫기, 탭 이동
sillon
sillon
꾸준해지려고 합니다..
    반응형
  • sillon
    sillon coding
    sillon
  • 전체
    오늘
    어제
    • menu (614)
      • notice (2)
      • python (68)
        • 자료구조 & 알고리즘 (23)
        • 라이브러리 (19)
        • 기초 (8)
        • 자동화 (14)
        • 보안 (1)
      • coding test - python (301)
        • Programmers (166)
        • 백준 (76)
        • Code Tree (22)
        • 기본기 문제 (37)
      • coding test - C++ (5)
        • Programmers (4)
        • 백준 (1)
        • 기본기문제 (0)
      • 공부정리 (5)
        • 신호처리 시스템 (0)
        • Deep learnig & Machine lear.. (41)
        • Data Science (18)
        • Computer Vision (17)
        • NLP (40)
        • Dacon (2)
        • 모두를 위한 딥러닝 (강의 정리) (4)
        • 모두의 딥러닝 (교재 정리) (9)
        • 통계 (2)
      • HCI (23)
        • Haptics (7)
        • Graphics (11)
        • Arduino (4)
      • Project (21)
        • Web Project (1)
        • App Project (1)
        • Paper Project (1)
        • 캡스톤디자인2 (17)
        • etc (1)
      • OS (10)
        • Ubuntu (9)
        • Rasberry pi (1)
      • App & Web (9)
        • Android (7)
        • javascript (2)
      • C++ (5)
        • 기초 (5)
      • Cloud & SERVER (8)
        • Git (2)
        • Docker (1)
        • DB (4)
      • Paper (7)
        • NLP Paper review (6)
      • 데이터 분석 (0)
        • GIS (0)
      • daily (2)
        • 대학원 준비 (0)
      • 영어공부 (6)
        • job interview (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    소수
    백준
    programmers
    Python
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
sillon
[Python] 웹 자동화 기초 - 경고창 이동, 쿠키, 자바스크립트 코드 실행
상단으로

티스토리툴바