2일차 - 네이버 기사를 크롤링해서 자신에게 메일 보내기

김몬지·2021년 9월 15일
0
post-thumbnail

오늘 한 건 네이버 기사를 크롤링해서 엑셀에 저장하고 메일로 보내기. 메일로 보내지는 것까지 확인했지만 우선 보안을 위해 지웠다.
튜터님이 설명해주신 것과 네이버 뉴스 창이 좀 리뉴얼되어있었는데, 그래도 찾기 어렵진 않았다.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from bs4 import BeautifulSoup
from selenium import webdriver
from openpyxl import Workbook

driver = webdriver.Chrome('chromedriver')

url = "https://search.naver.com/search.naver?where=news&sm=tab_jum&query=%EC%B6%94%EC%84%9D"

driver.get(url)
req = driver.page_source
soup = BeautifulSoup(req, 'html.parser')

articles = soup.select('#main_pack > section.sc_new.sp_nnews._prs_nws > div > div.group_news > ul > li')

wb = Workbook()
ws1 = wb.active
ws1.title = "articles"
ws1.append(["제목", "링크", "신문사"])

for article in articles:
  title = article.select_one('.news_area > a').text
  url = article.select_one('.news_area > a')['href']
  comp = article.select_one('a.info.press').text.split(' ')[0].replace('언론사', '')
  thumb = article.select_one('a.dsc_thumb > img')['src']
  ws1.append([title, url, comp, thumb])

driver.quit()
wb.save(filename='articles.xlsx')

# 보내는 사람 정보
me = "보내는 메일 주소"
my_password = "비밀 번호"

# 로그인하기
s = smtplib.SMTP_SSL('smtp.gmail.com')
s.login(me, my_password)

# 받는 사람 정보
emails = ['받는 메일 주소']

for you in emails:
  # 메일 기본 정보 설정
  msg = MIMEMultipart('alternative')
  msg['Subject'] = "제목"
  msg['From'] = me
  msg['To'] = you

  # 메일 내용 쓰기
  content = "메일 내용"
  part2 = MIMEText(content, 'plain')
  msg.attach(part2)

  part = MIMEBase('application', "octet-stream")
  with open("articles.xlsx", 'rb') as file:
      part.set_payload(file.read())
  encoders.encode_base64(part)
  part.add_header('Content-Disposition', "attachment", filename="추석기사.xlsx")
  msg.attach(part)

  # 메일 보내고 서버 끄기
  s.sendmail(me, you, msg.as_string())

s.quit()
profile
프론트엔드 공부하는 사람

0개의 댓글