ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python 기초 : 크롤링(Crawling), 인코딩(Encoding), 디코딩(Decoding)
    BootCamp/FastCampus x Upstage AI Lab 6기 2024. 11. 21. 17:04

    오늘 수업에서 Selenium과 BeautifulSoup을 사용해서 데이터 수집하는 크롤링(Crawling)과 온라인 수업에서 다룬 텍스트/이미지 인코딩(Encoding)과 디코딩(Decoding)을 함께한 혼자 해본 미니 실습 기록입니다.

    1. 데이터 수집
      • 네이버 뉴스 기사 : 텍스트, 이미지
    2. 인코딩
      • 텍스트
      • 이미지
    3. 디코딩
      • 텍스트
      • 이미지

    데이터 수집

    Selenuim은 웹 브라우저를 자동으로 제어할 수 있게 해주는 도구입니다. 웹페이지에서 동적으로 로드되는 콘텐츠(예: JavaScript를 통해 생성된 데이터)를 가져오거나 사용자 동작을 자동화하는 데 적합합니다.

     

    • 주요 기능: 브라우저 열기, 버튼 클릭, 스크롤, 입력 필드에 값 입력 등.
    • 활용 사례: 로그인 자동화, 동적 웹페이지 크롤링, 테스트 자동화.

     

    참고 자료:

    from bs4 import BeautifulSoup
    import requests
    
    # 뉴스 URL
    url = "https://n.news.naver.com/mnews/article/584/0000029642?sid=110"
    
    # HTTP 요청
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    
    # BeautifulSoup으로 HTML 파싱
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 기사 제목 추출
    title = soup.find('h2', {'class': 'media_end_head_headline'}).get_text(strip=True)
    
    # 기사 본문 추출
    content = soup.find('div', {'id': 'newsct_article'}).get_text(strip=True)
    
    # 출력 확인
    print(f"제목: {title}")
    print(f"본문: {content}")
    
    # img 태그 찾기
    image_tag = soup.find('img', {'class': '_LAZY_LOADING _LAZY_LOADING_INIT_HIDE'})
    
    # 이미지 URL 추출
    if image_tag and 'data-src' in image_tag.attrs:
        image_url = image_tag['data-src']
        print(f"이미지 URL: {image_url}")
    else:
        print("이미지 태그를 찾을 수 없습니다.")
    
    save_path = "news_image.jpg"  # 저장할 파일 경로
    
    # 이미지 다운로드 및 저장
    try:
        response = requests.get(image_url, stream=True)  # 스트리밍 방식으로 요청
        if response.status_code == 200:  # 요청 성공 여부 확인
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(1024):  # 데이터 청크 단위로 읽기
                    f.write(chunk)
            print(f"이미지 저장 완료: {save_path}")
        else:
            print(f"이미지 다운로드 실패. 상태 코드: {response.status_code}")
    except Exception as e:
        print(f"오류 발생: {e}")

    BeautifulSoup은 HTML과 XML 문서를 파싱(parsing)하고 특정 태그나 내용을 쉽게 추출할 수 있도록 도와주는 Python 라이브러리입니다.

    • 주요 기능: HTML 구조 분석, 태그/속성 검색, 텍스트 추출.
    • 활용 사례: 정적 웹페이지에서 데이터 크롤링, 웹 문서 데이터 전처리.

    참고 자료:

    인코딩(Encoding)

    인코은 데이터를 특정 형식으로 변환하는 과정입니다. 텍스트 데이터를 컴퓨터가 이해할 수 있는 바이너리 형식(예: UTF-8, ASCII)으로 변환하거나, 데이터 전송을 위해 Base64로 변환할 때 사용됩니다.

    • 주요 활용: 데이터 전송, 파일 저장, 네트워크 프로토콜에서 사용.
    import base64
    from PIL import Image
    
    # 한글 -> 바이너리로 인코딩
    utf_title_en = title.encode('utf-8')
    utf_content_en = content.encode('utf-8')
    print(utf_title_en)
    print(utf_content_en)
    
    # base64 인코딩
    title_en = base64.b64encode(utf_title_en)
    content_en = base64.b64encode(utf_content_en)
    print(title_en)
    print(content_en)
    
    # 이미지 -> 바이너리로 인코딩
    ima_path = 'news_image.jpg'
    img = Image.open(ima_path)
    
    #바이너리 파일 읽기 및 인코딩
    with open(ima_path, 'rb') as img:
        image = img.read()
        ima_en = base64.b64encode(image)
        print(ima_en)

    디코딩(Decoding)

    디코딩은 인코딩된 데이터를 원래의 형태로 변환하는 과정입니다. 네트워크를 통해 전달된 Base64 데이터나 바이너리 파일을 읽을 때 사용됩니다.

    • 주요 활용: 인코딩된 파일 복원, Base64 데이터 처리, 원본 텍스트 복구.
    # 기사 제목, 내용 디코딩
    import base64
    decode_title = base64.decodebytes(title_en)
    decode_content = base64.decodebytes(content_en)
    
    fin_decode_title = decode_title.decode('utf-8')
    fin_decode_content = decode_content.decode('utf-8')
    
    # 이미지 디코딩 및 저장
    path = 'news/image.jpg'
    with open(path, 'wb') as f:
        decoded_data = base64.decodebytes(ima_en)  # ima_en 전체를 디코딩
        f.write(decoded_data)
Designed by Tistory.