ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] selenium
    Back/Python 2022. 12. 21. 22:17

    Selenium

    • 웹 브라우저 자동화 라이브러리, 브라우저 동작을 자동화하여 웹 페이지를 테스트하거나 스크래핑 할 수 있다
    • 다양한 언어를 지원한다 (Java, C #, Python, Ruby, JavaScript, PHP)
    • 다양한 브라우저에서 작동할 수 있다 (Firefox, Chrome, IE, Edge)
    • 브라우저 별 WebDriver 와 통신하여 브라우저를 제어해 비교적 느리다

     

    Selenium 와 유사한 라이브러리

    puppeteer - 구글에서 만든 웹 브라우저(Chromium) 자동화 도구
    - 브라우저에서 코드를 직접 수행하여 빠르다
    - Node.js 만 지원한다
    playwright - MS에서 만든 웹 브라우저 자동화 도구
    - 멀티 프로세스 아키텍쳐로 구현되어 병렬작업이 가능하다
    - 비동기 API를 지원한다
    - 다양한 브라우저와 언어를 지원한다
    - 러닝커브가 높다

     

    Selenium 와 함께 쓰는 라이브러리

     

    webdriver_manager

    • 적절한 드라이버를 자동으로 다운로드하고 관리하는 파이썬 라이브러리
    • 드라이버를 로컬에 직접 설치하지 않아 버전관리의 번거로움을 줄 수 있다

     


     

    #cli> pip install selenium webdriver_manager
    
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from webdriver_manager.chrome import ChromeDriverManager
    from selenium.webdriver.common.by import By #
    
    with webdriver.Chrome(service=Service(ChromeDriverManager().install())) as driver:
    	driver.get("<https://www.example.com>")
        p = driver.find_element(By.TAG_NAME, 'p')
        pl = [e.text for e in driver.find_elements(By.TAG_NAME, 'p')]
    webdriver.Chrome()  - Chrome 을 실행하는 웹 드라이버 객체를 반환한다
    - 객체가 소멸할 때까지 브라우저 창이 유지 된다
    driver.get(url) - URL의 웹 페이지를 로드한다
    driver.find_element(By, val)
    driver.find_elements(By, val)
    - 조건에 일치하는 element를 반환한다
    - 일치하는 항목이 없을 경우 예외를 발생한다 NoSuchElementException
    - (By : 조건 키 집합)

     

    동적 스크래핑을 위한 Wait 

    구현 방법 설명
    driver.implicitly_wait(s) Implicit Wait
    (암묵적 기다림)
    - 페이지/요소 로드될 때까지 지정된 시간을 대기
    - 시간 내에 로드가 안된 경우 예외 발생
    WebDriverWait(driver, s)
    WebDriverWait(driver, s).until(target)  Explicit Wait
    (명시적 기다림)
    - 특정 요소에 대한 제약을 두어 기다림
    until 을 이용한 경우 target 요소를 반환
    WebDriverWait(driver, s).until_not(target)
    from selenium.webdriver.support import expected_conditions as EC
    
    driver.get("<https://indistreet.com/live>")
    xpath = '//*[@id="__next"]/div/main/div[2]/div/div[4]/div[1]/div[1]/div/a/div[1]/div/span/img'
    first_img = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))

     

    Mouse , Keyboard Event

    from selenium.webdriver import ActionChains
    
    # 마우스 이벤트
    btn = driver.find_element(By.XPATH, xpath)
    ActionChains(driver).click(btn).perform()
    
    # 키보드 이벤트
    id_input = driver.find_element(By.NAME, 'email')
    ActionChains(driver).send_keys_to_element(id_input, "Jhon")

     

    ElementNotInteractableException

    • 웹 페이지에서 요소가 존재하지만 상호작용이 불가능한 경우 발생하는 예외
    • 요소가 화면에 표시되었지만 사용자 입력이나 클릭과 같은 작업을 수행할 수 없을 때 발생한다
    • 사용 가능한 상태가 될 때까지 명시적인 대기 (Explicit Wait)를 사용하여 기다려야 한다

    'Back > Python' 카테고리의 다른 글

    [Python] BeautifulSoup  (0) 2023.04.19
    [Python] requests  (0) 2022.12.20
    [Error] pg_config executable not found.  (1) 2022.10.05
Designed by Tistory.