파이썬기초87 : 네이버의 뉴스들을 제목별로 docx문서로 저장하기
작성자 정보
- 관리자 작성
- 작성일
컨텐츠 정보
- 2,737 조회
- 0 추천
- 목록
본문
# pip install python-docx 설치
import requests
from bs4 import BeautifulSoup
import docx
# crawling
print("Getting list of articles...")
#네이버 뉴스페이지
response = requests.get("http://news.naver.com/main/list.nhn?sid1=105&mid=sec&mode=LSD&date=20160127&page=1")
response.raise_for_status()
# soup에는 지정했던 웹페이지의 내용이 html로 담겨있음.
soup = BeautifulSoup(response.text, "html.parser")
art_list = soup.select('.type06_headline > li > dl > dt > a')
art_list.extend(soup.select('.type06 > li > dl > dt > a'))
# art_list 라는 리스트에는 <a href="...."> ..... </a> 이 값으로 저장되어 있음.
real_list = [] #art_list에서 원하는 값들만 뽑아서 저장할 real_list 리스트
for art in art_list:
real_list.append(art['href'])
# doc writing
doc = docx.Document()
print("Writing articles to docs...")
for i in set(real_list):
response = requests.get(i)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
title = soup.select('#articleTitle')[0].get_text()
#print(title)
content = soup.select('#articleBodyContents')[0].get_text()
#print(content)
doc.add_heading(title, 0)
doc.add_paragraph(content)
doc.add_page_break()
print("Now saving...")
doc.save('articles.docx')
print("Done")
관련자료
-
이전
-
다음