스파르타코딩클럽 이벤트 참여 2일차

CH_Hwang·2021년 9월 11일
0

웹스크래핑 2일차 수업을 듣고 쓰는 일지

openpyxl, email, bs4, selenium, smtplib 모듈을 사용했다.

특정 페이지를 열고 그 페이지에서 해당되는 부분의 태그를 스크래핑했다.

이때 그 전 스크래핑과 다른점은 태그의 번호가 일정하지 않아서 특정 id로는 for문을 돌리기가 어려워서 li태그로 먼저 크롤리을 하고 그 결과를 for문을 돌려서 다시한번 스크래핑을 해주는 방식으로 웹 스크래핑을 진행했다.

그리고 그 결과를 openpyxl 모듈로 엑셀에 저장을 해주었다.

from openpyxl import Workbook

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

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

openpyxl 예제코드

그리고 smtplib 모듈을 사용하여 이메일 서버에 접속을 했고 이메일을 보내고 파일을 첨부하는 작업도 진행했는데, 이때 gmail의 경우에는 2단계보안과 보안 수준이 낮은 앱의 액세스를 허용해 주어야만 했다.

전체코드는 아래와 같다..

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


driver = webdriver.Chrome('chromedriver')

url = "https://search.naver.com/search.naver?where=news&sm=tab_jum&query=추석"

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(["제목", "링크", "신문사", "썸네일"])
# thumbnail = soup.select_one('#sp_nws1 > div.news_wrap.api_ani_send > a > img')['src']
# print(thumbnail)

for article in articles:
    title = article.select_one('div.news_wrap.api_ani_send > div > a').text
    url = article.select_one('div.news_wrap.api_ani_send > div > a')['href']
    news = article.select_one('div.news_wrap.api_ani_send > div > div.news_info > div.info_group > a').text.split(' ')[0].replace('언론사', '')
    thumbnail = article.select_one('div.news_wrap.api_ani_send > a > img')['src']
    ws1.append([title, url, news, thumbnail])

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


# 보내는 사람 정보
me = "메일@도메인"
my_password = "비밀번호"

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

# 받는 사람 정보
emails = ['메일@도메인', '메일2@도메인']
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()

0개의 댓글