from openpyxl import Workbook
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome('./chromedriver')
url = "https://search.naver.com/search.naver?where=news&sm=tab_jum&query=추석"
# url
driver.get(url)
req = driver.page_source
soup = BeautifulSoup(req, 'html.parser')
articles = soup.select('#main_pack > div.news.mynews.section._prs_nws > ul > li')
# 코드 검사 > copy select (안에 가져올 코드가 어떤 것인지 확인) > ul 안에 > li 코드 가져와서 저장
wb = Workbook()
ws1 = wb.active
ws1.title = "articles"
# 엑셀 파일 이름
ws1.append(["제목", "링크", "신문사"])
# 엑셀 1번째 가로 줄에 append
for article in articles:
title = article.select_one('dl > dt > a').text
# article 에서 dl > dt > a 의 text 만 저장
url = article.select_one('dl > dt > a')['href']
# article 에서 dl > dt > a 에서 href 만 저장 (title)
comp = article.select_one('span._sp_each_source').text.split(' ')[0].replace('언론사' , '')
# article 에서 언론사 copy select 하여 text 만 저장 후 split (' ' 공백으로 자르기) 후 [0] 처음것만 가져오기
# replace '언론사' 는 '' 공백으로 표시
ws1.append([title, url, comp])
# 엑셀에 첫번째 가로줄에 append
driver.quit()
wb.save(filename='articles.xlsx')
# 엑셀에 저장하기
homework 썸네일 추가하여 코드 작성하기
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome('./chromedriver')
from openpyxl import Workbook
wb = Workbook()
ws1 = wb.active
ws1.title = "homework"
ws1.append(["제목", "링크", "신문사", "썸네일"])
url = "https://search.naver.com/search.naver?sm=tab_hty.top&where=news&query=%EC%BD%94%EB%A1%9C%EB%82%98"
driver.get(url)
req = driver.page_source
soup = BeautifulSoup(req, 'html.parser')
news = soup.select('#main_pack > div > ul > li')
for new in news:
title = new.select_one ('dl > dt > a').text
url = new.select_one('dl > dt > a')['href']
comp = new.select_one('span._sp_each_source').text.split(' ')[0].replace('언론사', ' ')
img = new.select_one('div > a > img')['src']
ws1.append([title, url, comp, img])
wb.save(filename='homework2.xlsx')
driver.quit()
이메일 보내기, 첨부파일 보내기
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
# 보내는 사람 정보
me = "cs982606@gmail.com"
my_password = ""
# 로그인하기
s = smtplib.SMTP_SSL('smtp.gmail.com')
s.login(me, my_password)
# 받는 사람 정보
emails = ["cs982606@gmail.com" ,"cs982606@gmail.com" ]
# 여러 사람에게 보내
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("homework2.xlsx", 'rb') as file:
# 엑셀 파일 이름
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment", filename="코로나 기.xlsx")
# 엑셀 파일이름 변경 후 메일 전송
ms.attach(part)
# 메일 보내고 서버 끄기
s.sendmail(me, you, msg.as_string())
s.quit()
# 2중인증 해제 , 보안 수준 낮은 앱 해제 하기
# https://myaccount.google.com/signinoptions/two-step-verification 2증인증
# https://myaccount.google.com/lesssecureapps 보안 수준 낮은 앱 해제하기