본문 바로가기

Backend/Python

(14)
첫코딩 : 스레드(thread) thread(스레드) : 실, 가닥, 줄기 threading(스레싱) : 조각조각 나눠서 따로 사용하는 행위 multi threading(멀티 스레딩) : 컴퓨터가 업무를 동시에 하는 것이 아니라 여러가지 업무를 번갈아가며 하는데, 우리 눈에는 마치 동시에 하는 것처럼 보인다. import threading # threading 패키지 불러오기 class count(threading.Thread): # Thread 클래스 상속받기 def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): # 호출 이름 : run for i in range(0, 5): print(self.name, i) first = c..
첫코딩 : 배스킨라빈스31 게임 from random import * print('game start') cnt = 1 while True: while True: # 에러 처리 try: N = int(input('[Player1] How many do you count(1~3):')) if N >= 1 and N = 31: break N = randint(1, 3) # 컴퓨터 참가자 추가 print('[computer]How many do you count?:{}'.format(N)) for i in range(N): print('{}'.format(cnt+i), end=" ") print() cnt = cnt + N if cnt >= 31: break print('game over') # 예외처리부분 함수처리로 코드 단순화 from ..
웹크롤링 3. 셀레니움으로 네이버 상품정보 수집 Why 셀레니움 ? : requests의 한계 1. 로그인이 필요한 사이트에서 크롤링이 어려움 2. 동적으로 html을 만드는 경우 : 스크롤하거나 클릭하면 데이터가 생성, url주소가 변경되지 않았는데 데이터가 변경 What is 셀레니움 ? 1. 웹 어플리케이션 테스트를 위한 도구 2. 브라우저를 실제로 띄워서 사람처럼 동작하도록 만들 수 있음. 1. 셀레니움 설치 크롬 드라이버 다운로드 → C드라이브로 복사 라이브러리 설치 - pip install selenium 2. 네이버 쇼핑 검색 from selenium import webdriver from selenium.webdriver.common.keys import Keys #ENTER를 입력하기 위함 import time # 브라우저 생성 bro..
웹크롤링 2.주식현재가 엑셀로 저장하기 1. 네이버에서 주식 현재가 수집하기 import requests from bs4 import BeautifulSoup codes = [ '005930', #삼성전자 '263750', #펄어비스 '035720' #카카오 ] for code in codes: url = f"https://finance.naver.com/item/sise.naver?code={code}" response = requests.get(url) html = response.text soup = BeautifulSoup(html, 'html.parser') price = soup.select_one("#_nowVal").text price = price.replace(',', '') print(price) 2. 엑셀 만들기 impo..
웹크롤링 1. 뉴스제목+링크 가져오기 1. html을 파이썬으로 가져오기 : requests import requests response = requests.get("http://www.naver.com") html = response.text print(html) 2. 원하는 태그를 선택하기 : Beautifulsoup import requests # no module named 'bs4'일 경우 : 터미널에 pip install bs4 입력 from bs4 import BeautifulSoup # naver 서버에 대화를 시도 response = requests.get("http://www.naver.com/") # naver 에서 html 줌 html = response.text # html 번역선생님(html.parser)으로 수프 ..
모듈 모듈 : 필요한 부분만 다른 파일에 만드는 것 # theater_module.py # 일반 가격 def price(people): print("{0}명 가격은 {1}원입니다.".format(people, people * 10000)) # 조조 할인 가격 def price_morning(people): print("{0}명 조조 할인 가격은 {1}원입니다.".format(people, people * 6000)) # 군인 할인 가격 def price_soldier(people): print("{0}명 군인 할인 가격은 {1}원입니다.".format(people, people * 4000)) # practice.py import theater_module theater_module.price(3) theat..
예외처리 try, except # 예외처리(숫자를 한글이나 0으로 입력할 때) try: print("나누기 전용 계산기입니다.") nums = [] nums.append(int(input("첫 번째 숫자를 입력하세요 : "))) nums.append(int(input("두 번째 숫자를 입력하세요 : "))) # nums.append(int(nums[0] / nums[1])) print("{0} / {1} = {2}".format(nums[0], nums[1], nums[2])) except ValueError: print("에러! 잘못된 값을 입력하였습니다.") except ZeroDivisionError as err:6 print(err) # 정확한 에러 메시지 출력(division by zero) except..
클래스 from random import * # 일반 유닛 class Unit: def __init__(self, name, hp, speed): # 생성자 self.name = name self.hp = hp self.speed = speed print("{0}유닛이 생성되었습니다.".format(name)) def move(self, location): print("{0} : {1} 방향으로 이동합니다. [속도 {2}]" .format(self.name, location, self.speed)) def damaged(self, damage): print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage)) self.hp -= damage print("{0} : 현재 체력..