[Python] 크롤링 엑셀 파일 만들기

2023. 4. 17. 22:48Language/Python

크롤링 Excel 파일로 저장하는 방법

import openpyxl # 임포트 해주기

excel_file = openpyxl.Workbook() # 엑셀 파일 생성

excel_sheet = excel_file.active # 시트 가져오기

 

sheet 이름 변경 방법

excel_sheet.title = '리포트' #시트 이름 변경

 

데이터 넣는방법

excel_sheet.append(['data1', 'data2', 'data3']) #리스트로 데이터 넣어주기

 

실제 데이터 삽입 결과

  A B C
1 data1 data2 data3

두번 삽입 했을때 결과

  A B C
1 data1 data2 data3
2 data1 data2 data3

 

저장 방법

excel_file.save('test.xlsx') # 엑셀 파일 저장

 

엑셀 파일 닫기

excel_file.close() # 엑셀 파일 닫기

 

 

크롤링 해서 엑셀 파일 만들어보기

 

함수 설정

import openpyxl

def write_excel_template(filename, sheetname, listdata): # 파일 이름, 시트 이름, 넣을 데이터
    excel_file = openpyxl.Workbook() # 파일 만들기
    excel_sheet = excel_file.active # 파일 시트
    excel_sheet.column_dimensions['A'].width = 100 # A셀 가로 크기 설정
    excel_sheet.column_dimensions['B'].width = 20 # B셀 가로 크기 설정
    
    if sheetname != '': # 시트네임 빈문자열이 아니라면
        excel_sheet.title = sheetname 
    
    for item in listdata:
        excel_sheet.append(item) # 리스트 집어 넣기
    excel_file.save(filename)
    excel_file.close()

 

엑셀에 넣을 데이터 크롤링

import requests
from bs4 import BeautifulSoup

product_lists = list()

for page_num in range(1,6):
    res = requests.get(' https://taehee98.tistory.com/?page=' + str(page_num))
    soup = BeautifulSoup(res.content, 'html.parser')

    data = soup.select('ul > li > a > div')
    for item in data:
        product_name = item.select_one('ul > li > a > div > strong')
        product_date = item.select_one('ul > li > a > div > span')
        product_info = [product_name.get_text().strip(), product_date.get_text()]
        product_lists.append(product_info)

 

엑셀에 데이터 넣기

write_excel_template('tmp.xlsx', '개발일기 title, date', product_lists)

 

결과

엑셀 파일 읽기

excel_file = openpyxl.load_workbook('tmp.xlsx') # 읽을 파일 넣기

excel_file.sheetnames # 쉬트 이름 확인 (리스트 타입으로 리턴됨)

['개발일기 title, date']

excel_sheet = excel_file["개발일기 title, date"] # 시트 안에 있는 데이터 읽기

for item in excel_sheet.rows:
    print(item[0].value, item[1].value)

[Python] 크롤링 엑셀 파일 만들기 2023.04.17
[Python] 크롤링 패턴 실습 2023.04.11
[Python] 객체와 라이브러리 2023.04.11
[Python] jupyter notebook 기본 사용법 Python 문법 2023.03.31
[SQLD] SQL 최적화 기본 2023.03.13
[SQLD] 데이터 모델과 성능 2023.02.28
[SQLD] 데이터 모델링의 이해 2023.02.07
[SQLD] SQLD 문제 풀이 2023.02.01
[Linux] 리눅스 명령어 정리 2023.01.26
[Vue.js] vue3에서 quill editor 사용방법 2022.12.01
[Vue.js] Vue 프로젝트 설정 2022.11.28
[Vue.js] Vue 프로젝트 생성 방법 2022.11.28
[Node.js] 버전 다운그레이드 방법 2022.11.23
[MyBatis] MyBatis 정의 및 주요 메서드 2022.11.23
[Spring] AOP 개념 및 구현 2022.11.23
[Spring] @Autowired 와 DI 개념 정리 2022.11.23
[Spring][JAVA] Spring 개념 정리 (AOP,POJO,JDBC 등) 2022.11.23
[Spring] 메이븐(Maven)과 pom.xml 2022.11.23
MVC 정리 2022.11.23
[Spring] 전자정부프레임워크란? 2022.11.23
[Spring] Spring 기초 정리 2022.11.23
[JSP] 서블릿(Servlet)이란? 2022.11.23
[Vue.js] Vue 정리 (2022-11-17) 2022.11.23
[Vue.js] Vue 정리 (2022-11-16) 2022.11.23
[Vue.js] Vue 정리 (2022-11-11) 2022.11.23

 

엑셀 파일 읽기 전체 코드

import openpyxl

excel_file = openpyxl.load_workbook('tmp.xlsx')
excel_sheet = excel_file.active

for row in excel_sheet.rows:
    print(row[0].value, row[1].value)

excel_file.close()

반응형