AR삽질러

Python - 웹 크롤링 본문

Python

Python - 웹 크롤링

아랑팡팡 2023. 12. 9. 14:46
728x90

 

웹 크롤링

 웹(WWW, Web)에 있는 데이터들을 가져오는 기술을 크롤링이라고 한다. 웹 페이지들은 하이퍼링크를 이용하여 하이퍼텍스트 공간을 자유롭게 이동할 수 있다. 이렇게 웹에 연결된 문서들로부터 필요한 정보를 자동, 반자동으로 수집하는 것을 웹크롤링(Web Crawling)이라고 한다. 이때 수집하는 역할을 처리하는 컴퓨터 프로그램을 웹크롤러, 웹봇 등 다양한 이름으로 불린다. 웹 페이지의 HTML구조를 분석하여 (HTML 파싱) 필요한 정보만을 추출할 수 있는데 이 때 유용하게 사용하는 라이브러리가 BeautifulSoup이다. 이 라이브러리 설치 명령은 "pip install beautifulsoup4"이다. 

 

1. 투믹스 웹툰 제목 가져오기

import requests
from bs4 import BeautifulSoup

url = "https://www.toomics.com/webtoon/weekly/dow/1" # 아무의미 없는 문자열 이기 때문에
res = requests.get(url)
res.raise_for_status()

soup = BeautifulSoup(res.text, 'html.parser')

webtoons = soup.find_all("strong", attrs={"class": "toon-dcard__title"})

print("---투믹스 수요일 웹툰 제목 리스트----")
for webtoon in webtoons:
    print(webtoon.get_text().strip())

 

투믹스 웹사이트 수요일 웹툰 제목 크롤링

1) 라이브러리

 requests : 웹 페이지의 내용을 가져오기위해 HTTP요청을 하는 라이브러리

 from bs4 import BeautifulSoup : HTML과 XML파일을 파싱하기 위한 라이브러리

 

2) 웹 페이지 요청 및 응답

 url : 크롤링을 위한 URL

 res = requests.get(url) : 투믹스 수요일 웹툰 페이지에 접근 

 res.raise_for_status() : 요청을 확인

 

3) HTML파싱

 soup = BeautifulSoup(res.text, 'html.parser') : res.text는 requests.get함수로 받아온 웹페이지의 HTML내용을 파싱

 

4) 웹 툰제목 추출

 webtoons = soup.find_all("strong", attrs={"class" : "toon-dcard__title") : 해당 HTML내에서 class가 toon-dcard_title인 strong태그를 모두 찾아 webtoons 리스트에 저장한다.

 

5) 제목 출력

 webtoon : 리스트에 저장된 웹툰 제목을 출력

 get_text().strip() : strong태그의 공백을 제거한 텍스트 내용만 추출

 

2. 할리스 매장의 정보(매장명, 전화번호, 주소 등)를 크롤링해 CSV파일로 저장하기

from bs4 import BeautifulSoup
import urllib.request
import pandas as pd

def hollys_store(result):
    for page in range(1, 10):
        Hollys_url = 'https://www.hollys.co.kr/store/korea/korStore.do?pageNo=%d&sido=&gugun=&store=' % page
        print(Hollys_url)
        html = urllib.request.urlopen(Hollys_url)
        soupHollys = BeautifulSoup(html, 'html.parser')
        tag_tbody = soupHollys.find('tbody')
        for store in tag_tbody.find_all('tr'):
            if len(store) <= 3:
                break
            store_td = store.find_all('td')
            store_name = store_td[1].string
            store_sido = store_td[0].string
            store_address = store_td[3].string
            store_phone = store_td[5].string
            result.append([store_name] + [store_sido] + [store_address] + [store_phone])
    return



def main():
    result = []
    print('Hollys store crawling >>>>>>>>>>>>>>>>>>>>>>>>>>')
    hollys_store(result)  
    hollys_tbl = pd.DataFrame(result, columns=('store', 'sido-gu', 'address', 'phone'))
    hollys_tbl.to_csv('c:/Temp/hollys.csv', encoding='cp949', mode='w', index=True)
    del result[:]


if __name__ == '__main__':
    main()

 

 

hollys.csv
0.01MB

 

프로그램 흐름

 - main함수 호출 후 hollys_store 함수에서 각각의 페이지에 대한 정보를 수집한다음 수집된 데이터는 pandas DataFrame으로 변환되어 CSV파일로 저장된다.

 

1) 라이브러리 

BeautifulSoup : HTML과 XML파일을 파싱하기위한 라이브러리로 HTML구조를 분석하고 데이터를 추출하는데 사용된다.

urllib.request : URL에서 데이터를 읽기 위한 모듈

pandas : 데이터 분석을 위한 라이브러리로 데이터 조작 및 분석을 위한 DataFrame객체를 제공

 

2) 함수

hollys_store : 할리스 매장 정보를 크롤링한다.

def hollys_store(result):
	for page in range(1, 10):

 for : 1 ~ 10페이지를 순화하며 Hollys_url 페이지에 대한 URL을 생성한다.

 html = urllib.request.urlopen(Hollys_url) : 해당 URL의 HTML내용을 가져온다.

 soupHollys = BeautifulSoup(html, 'html.parser') : html에 가져온 HTML을 파싱한다.

 tag_tbody = soupHollys.find('tbody') : 각 페이지의 매장 정보가 담긴 tbody를 찾는다.

 for store in tag_tbody.find_all('tr') : tbody의 태그에 모든 tr태그를 순회하며 매장 이름, 지역, 주소, 전화번호를 출력해 result 리스트에 추가한다.

 

main : 크롤링 프로세스를 실행하고 결과를 저장한다.

 result = [] : hollys_store함수를 담을 빈리스트를 생성한다.

 hollys_tbl = pd.DataFrame(result, colums=('store', 'sido-gu', 'address', 'phone')) : 크롤링된 데이터를 pandas DataFrame을 만들로 이름을 지정한다.

 hollys_tbl.to.csv : 한글 인코딩 방지를 위해 cp949를 사용하고 데이터를 CSV파일로 저장한다.

 

프로그램 실행 시점

if __name__ == '__main__':
    main()

 Python 스크림트가 직접 실행될 때만 main함수를 호출하는 표준 Python패턴

 

 

 

 

728x90
반응형
LIST