ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] Selenium 크롤링
    Python 2023. 6. 28. 10:04

     

    Selenium이란?

    Selenium은 웹 애플리케이션의 자동화를 위한 도구로 사용되는 오픈 소스 프레임워크입니다. 웹 브라우저를 제어하여 웹 페이지의 동작을 시뮬레이션하고 테스트하는데 사용됩니다. Selenium을 사용하면 다양한 브라우저에서 동작하는 웹 애플리케이션을 테스트하고 검증할 수 있습니다.

     

    Selenium 설치

    pip install selenium
    # or
    conda install selenium
    

     

    Selenium 사용법

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    
    webdriver_path = r'drive경로'
    driver = webdriver.Chrome(options=options)
    
    driver.get("크롤링할 url")
    
    # 'h3'태그 중에 'title-cnt'클래스인 태그
    element = driver.find_element(By.CSS_SELECTOR, 'h3.title-cnt')
    
    # class가 'component_wra'인 모든 태그
    element = driver.find_elements(By.CSS_SELECTOR, '.component_wrap')
    
    # id가 'my-app'인 태그
    element = driver.find_element(By.CSS_SELECTOR, '#my-app')
    
    # 모든 div 태그
    element = driver.find_element(By.TAG_NAME, 'div')
    
            
    driver.close()
    

     

    iframe으로 구성된 페이지 크롤링

    <iframe> 요소는 웹 페이지 안에 다른 웹 문서를 포함시키기 위해 사용됩니다. Selenium을 사용하여 <iframe> 안에 포함된 내용을 가져오려면 다음과 같은 단계를 따를 수 있습니다:

    1. <iframe> 요소를 식별합니다.
    2. <iframe> 요소를 전환하여 해당 내용으로 포커스를 이동합니다.
    3. 포커스가 이동된 후에는 일반적인 방법으로 태그를 가져올 수 있습니다.
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    
    webdriver_path = r'drive경로'
    driver = webdriver.Chrome(options=options)
    
    driver.get("크롤링할 url")
    
    # iframe 요소 식별
    iframe = driver.find_element(By.ID, "mainFrame")
    
    # 포커스 전환
    driver.switch_to.frame(iframe)
    
    # 'h3'태그 중에 'title-cnt'클래스인 태그
    element = driver.find_element(By.CSS_SELECTOR, 'h3.title-cnt')
    
    # class가 'component_wra'인 모든 태그
    element = driver.find_elements(By.CSS_SELECTOR, '.component_wrap')
    
    # id가 'my-app'인 태그
    element = driver.find_element(By.CSS_SELECTOR, '#my-app')
    
    # 모든 div 태그
    element = driver.find_element(By.TAG_NAME, 'div')
    
    # 포커스 복원
    driver.switch_to.default_content()
    
    driver.close()
    
    728x90
Designed by Tistory.