내맘대로 코딩

[스파르타 내일배움] Python 1주차 - 파이썬기초, 업무자동화 본문

Python

[스파르타 내일배움] Python 1주차 - 파이썬기초, 업무자동화

Yoonjung 2023. 2. 20. 14:34

강의명 

[왕초보] 주식 데이터를 활용한 파이썬 데이터 분석 23회차 

이범규 튜터

 

강의자료 

https://www.notion.so/1-71164ea191994107ba1e0c73b29b0b5c?pvs=4 

 

[스파르타코딩클럽] 1주차 : 킹 받을 땐 파이썬 – 파이썬기초, 업무자동화

매 주차 강의노트 시작에 PDF파일을 올려두었어요!

www.notion.so


Weelky I learned 

 

구글 Colab

  • 브라우저 상에서 파이썬 코딩을 할 수 있게 해둔 환경!
  • (1) 내 컴퓨터에 파이썬을 설치 할 필요 없고, (2) 인터넷만 되면 어디서든 접근 가능하고, (3) 내 컴퓨터보다 빠르답니다!

 

파이썬 기초 

1) 변수 & 기본연산

a = 3      # 3을 a에 넣는다
b = a      # a를 b에 넣는다
a = a + 1  # a+1을 다시 a에 넣는다

num1 = a*b # a*b의 값을 num1이라는 변수에 넣는다
num2 = 99 # 99의 값을 num2이라는 변수에 넣는다

2) 리스트, 딕셔너리 형

- 리스트형은 순서가 중요 

a_list = ['사과','배','감','수박']

a_list[0]

a_list.append('귤')

a_list[4]

-딕셔너리형은 { key : value } 형태가 중요 

a_dict = {'name':'bob','age':21}

a_dict['age']

a_dict['height'] = 178

a_dict

--> 

Dictionary 형과 List 형의 조합

people = [{'name':'bob','age':20},{'name':'carry','age':38}]

# people[0]['name']의 값은? 'bob'
# people[1]['name']의 값은? 'carry'

person = {'name':'john','age':7}
people.append(person)

# people의 값은? [{'name':'bob','age':20},{'name':'carry','age':38},{'name':'john','age':7}]
# people[2]['name']의 값은? 'john'

3) 함수

def sum(a,b):
	return a+b

def mul(a,b):
	return a*b

result = sum(1,2) + mul(10,10)

 

4) 조건문

if age > 20:
	print('성인입니다')    # 조건이 참이면 성인입니다를 출력
else:
	print('청소년이에요')  # 조건이 거짓이면 청소년이에요를 출력

is_adult(30)

 

5) 반복문

조건문 + 함수 + 반복문을 한번에 사용해보기

def check_adult(age):
	if age > 20:
		print('성인입니다')
	else:
		print('청소년이에요')

ages = [20,30,15,5,10]

for age in ages:
	check_adult(age)

 

업무자동화 - 웹 스크랩핑 

라이브러리 설치 : pip install bs4 requests

⇒ requests 로 정보를 가져와서 → BeautifulSoup으로 분석하기 좋게! 만드는 것이랍니다.

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query=삼성전자',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')
  1. 우선,이제 여러 개의 기사 제목을 가져와보겠습니다.
lis = soup.select('#main_pack > section > div > div.group_news > ul > li')

⇒ 2. 그리고 그 안에서 우리가 원하는 a 태그를 가져와보겠습니다.

lis[0].select_one('a.news_tit')

⇒ 3. 마지막으로 반복문을 활용해 정리할 수 있습니다.

lis = soup.select('#main_pack > section > div > div.group_news > ul > li')

for li in lis:
  a = li.select_one('a.news_tit')
  print(a.text, a['href'])

키워드만 바꿔 입력하면 뉴스를 볼 수 있게 만듬

-keyword 부분을 '현대자동차'로 입력시, 현대자동차와 관련한 뉴스 리스팅됨 

def get_news(keyword):
  headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
  data = requests.get(f'https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query={keyword}',headers=headers)

  soup = BeautifulSoup(data.text, 'html.parser')
  lis = soup.select('#main_pack > section > div > div.group_news > ul > li')

  for li in lis:
    a = li.select_one('a.news_tit')
    print(a.text, a['href'])

 

 

업무자동화 - 엑셀다루기 

openpyxl 라이브러리 설치 : pip install openpyxl

 

엑셀 파일 만들어보기

from openpyxl import Workbook

wb= Workbook()
sheet = wb.active

sheet['A1'] = '안녕하세요!'

wb.save("샘플파일.xlsx")
wb.close()

전체 데이터 읽기 

import openpyxl
wb = openpyxl.load_workbook('샘플파일.xlsx')
sheet = wb['Sheet']

for row in sheet.rows:
  print(row[0].value, row[1].value, row[2].value)

스크래핑 결과를 엑셀에 넣을 수도 있겠네요!

import requests
from bs4 import BeautifulSoup

from openpyxl import Workbook

wb = Workbook()
sheet = wb.active

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(f'https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query=삼성전자',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')
lis = soup.select('#main_pack > section > div > div.group_news > ul > li')

for li in lis:
  a = li.select_one('a.news_tit')
  row = [a.text, a['href']]
  sheet.append(row)

wb.save("샘플파일.xlsx")
wb.close()

함수로 만들어보기 

def make_news_excel(keyword):
  wb = Workbook()
  sheet = wb.active

  headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
  data = requests.get(f'https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query={keyword}',headers=headers)

  soup = BeautifulSoup(data.text, 'html.parser')
  lis = soup.select('#main_pack > section > div > div.group_news > ul > li')

  for li in lis:
    a = li.select_one('a.news_tit')
    row = [a.text, a['href']]
    sheet.append(row)

  wb.save(f"{keyword}.xlsx")
  wb.close()

 

 

 

이미지 다운로드 

import urllib.request

url = 'https://ssl.pstatic.net/imgfinance/chart/item/area/day/005930.png' #이미지 URL 넣기 
urllib.request.urlretrieve(url, "samsung.jpg") #파일저장명 지정

 

숙제 

엑셀 파일 종목들의 이미지를 한번에 다운로드 받아주세요!

 

1) 관리종목 파일 불러오기 + 정보 불러오기 

import openpyxl
wb = openpyxl.load_workbook('관리종목.xlsx')
sheet = wb['종목']

new_rows = list(sheet.rows)[1:]

for row in new_rows:
  print(row[0].value, row[1].value)

 

2) 네이버 주식에서 기업별 주식 이미지 파일들을 불러와서 저장 

import openpyxl
wb = openpyxl.load_workbook('관리종목.xlsx')
sheet = wb['종목']

new_rows = list(sheet.rows)[1:]

for row in new_rows:
  code = row[1].value  #code 변수 지정/1번쨰 열
  name = row[0].value  #name 변수 지정/2번쨰 열 
  url = f'https://ssl.pstatic.net/imgfinance/chart/item/area/day/{code}.png'
  urllib.request.urlretrieve(url, f"images/{name}.jpg")   #여러개 이미지 파일들을 생성

3) 여러 이미지 파일을 압축파일로 묶어서 저장

!zip -r /content/files.zip /content/images  #여러개 이미지 파일을 압축파일로 묶어 저장

[결과화면]