Data/Crawling

6. word 활용 (python-docx)

코딩마루 2024. 4. 6. 17:57

1. python-docx

python에서 워드를 활용하기 위해서는 python-docx 라이브러리를 사용할 수 있다. python-docx 설치를 위해 아래 명령어를 실행하면 된다.

pip install python-docx

기본적인 메서드에는 워드 객체를 생성하는 Document()와 제목을 작성하는 add_heading(), 본문을 작성하는 add_paragraph() 등이 있다. 예시 코드는 다음과 같다.

from docx import Document

# 1. 워드 생성
document = Document()

# 2. 워드에 데이터 추가
# level = 제목의 크기 (0 = 가장 크며 아래에 밑줄이 있다. 1~6으로 갈수록 크기가 작아진다.)
document.add_heading('제목', level = 0)

# 3. 문단 추가
# 문단이란 한줄로 이어지는 글을 말한다. 엔터를 치지 않은 상태를 의미한다.
document.add_paragraph('본문 내용')

# 4. 워드 저장
document.save("test.docx")

2. 크롤링 데이터 워드에 기록하기

이전에 뉴스 제목, url, 내용을 크롤링한 데이터를 워드로 아래와 같이 작성하여 저장할 수 있다.

import time

import requests
from bs4 import BeautifulSoup
from docx import Document

response = requests.get("https://search.naver.com/search.naver?ssc=tab.news.all&where=news&sm=tab_jum&query=%EC%82%BC%EC%84%B1%EC%A0%84%EC%9E%90")

html = response.text
soup = BeautifulSoup(html, "html.parser")
articles = soup.select("div.info_group")

document = Document()

for index, article in enumerate(articles):
    links = article.select("a.info")
    
    if len(links) < 2:
        continue
    
    url = links[1].attrs['href']
    
    response = requests.get(url)
    
    '''
    네이버가 봇으로 인지하는 경우 response의 결과를 받지 못하고 Connection aborted 오류가 발생한다.
    해당 경우 아래 코드 사용한다.
    '''
    # response = requests.get(url, headers={'User-agent':'Mozila/5.0'})
    
    html = response.text
    soup = BeautifulSoup(html, "html.parser")
    
    title = soup.select_one('#title_area').get_text().strip()
    contents = soup.select_one('#dic_area').get_text().strip()
    
    document.add_heading(title, level=0)
    document.add_paragraph(url)
    document.add_paragraph(contents)
    
    # 서버에 부담가지 않도록 하기위해 sleep을 사용한다.
    time.sleep(0.5)
    
document.save("test.docx")

참고자료: https://www.inflearn.com/course/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%ED%81%AC%EB%A1%A4%EB%A7%81-%EC%8B%A4%EC%A0%84/dashboard