개발자로 가는길 :: '개발/파이썬' 카테고리의 글 목록

파이썬 동행복권 로그인 / 충전페이지 이동 자동화

개발/파이썬|2023. 4. 26. 08:55
728x90
반응형
동행복권 로그인 / 충전 금액선택 / 충전 버튼까지
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import os
from tkinter import *


def start_process():
    # 크롬 웹드라이버 불러오기(같은폴더에 넣음)
    chromedriver_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "chromedriver"
    )
    driver = webdriver.Chrome(executable_path=chromedriver_path)

    # 로그인 페이지 접속
    driver.get("https://www.dhlottery.co.kr/user.do?method=login&returnUrl=")

    # 아이디 , 비번 입력받은 변수
    username = entry_username.get()
    password = entry_password.get()
    window.destroy()

    # 1. 페이지 접속이 완료되면 아이디 비번 입력
    username_field = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "input#userId"))
    )
    password_field = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='password']"))
    )

    username_field.send_keys(username)
    password_field.send_keys(password)

    # 로그인 버튼 클릭
    login_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn_common.lrg.blu"))
    )
    login_button.click()
    # 메인페이지로 돌아오면 충전 버튼 클릭
    time.sleep(2)
    recharge_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn_common.sml"))
    )
    recharge_button.click()

    # 2초 기다린후 5000원 선택 value값 자기가 원하는 값으로 변경
    time.sleep(2)
    select_amount = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "select#Amt"))
    )
    select_amount.find_element(By.CSS_SELECTOR, "option[value='5000']").click()

    # 충전 버튼 클릭
    ok_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable(
            (By.CSS_SELECTOR, "button[onclick='settleBankStart()']")
        )
    )

    ok_button.click()

    # 브라우저 종료여부 묻기
    close_browser = input("브라우저를 종료하시겠습니까? (yes/no): ").lower().strip()

    if close_browser == "yes":
        driver.quit()


# 메인 윈도우
window = Tk()
window.title("동행복권 자동화")
window.geometry("260x150")

# 아이디 테이블
Label(window, text="아이디:").grid(row=0, column=0, padx=10, pady=10, sticky=W)
entry_username = Entry(window)
entry_username.grid(row=0, column=1, padx=10, pady=10, sticky=W)
# 비밀번호 테이블
Label(window, text="비밀번호:").grid(row=1, column=0, padx=10, pady=10, sticky=W)
entry_password = Entry(window, show="*")
entry_password.grid(row=1, column=1, padx=10, pady=10, sticky=W)

# 시작 버튼
start_button = Button(window, text="매크로시작", command=start_process)
start_button.grid(row=2, column=1, padx=10, pady=10, sticky=E)

# 루프 시작
window.mainloop()
728x90
반응형

댓글()

.torrent 파일 일괄 삭제 프로그램 (파이썬 코드 , 실행파일 다운)

개발/파이썬|2023. 4. 15. 10:48
728x90
반응형

토렌트 이용을 많이 하다보니 여기저기 흩어져있는 ,torrent 파일을 윈도우 자체검색하니 시간이 너무 오래걸려서

어떻게 할까 고민을 하다가 파이썬에 모든 드라이브를 탐색할 수 있는 라이브러리가 있다는 걸 알게되어서

만들어 보았다.

 

import os

# 모든 드라이브에서 확장자가 '.torrent'인 파일들을 모두 찾아서 삭제
for root, dirs, files in os.walk("/"):
    for file in files:
        if file.endswith(".torrent"):
            os.remove(os.path.join(root, file))

모든 드라이브의 root , dirs , files 를 검색 해서 .torrent 파일을 삭제하는 코드 이다.

 

deltorrent.zip
16.19MB

dist 폴더에 있는 exe 파일 실행하면 되고 , 모든 드라이브를 검색하다보니 시간이 약간 걸릴 수 있다

내컴퓨터 기준 (i7 12세대 ,램32기가) 약 10초가 안걸린 것 같다.

따로 프롬프트창에 메시지를 띄우거나 하는 것은 아니기에 프롬프트 실행 -> 종료 되면 작업이 끝난 것 이다

728x90
반응형

댓글()

Python 인강 / 객체지향 커피머신 만들기

개발/파이썬|2023. 3. 22. 20:24
728x90
반응형
#메인 코드
from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

money_machine = MoneyMachine()
coffee_maker = CoffeeMaker()
menu = Menu()

is_on = True

while is_on:
    options = menu.get_items()
    choice = input(f"What would you like? ({options}): ")
    if choice == "off":
        is_on = False
    elif choice == "report":
        coffee_maker.report()
        money_machine.report()
    else:
        drink = menu.find_drink(choice)
        
        if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost):
          coffee_maker.make_coffee(drink)
#커피 만들기 클래스
class CoffeeMaker:
    """Models the machine that makes the coffee"""
    def __init__(self):
        self.resources = {
            "water": 300,
            "milk": 200,
            "coffee": 100,
        }

    def report(self):
        """Prints a report of all resources."""
        print(f"Water: {self.resources['water']}ml")
        print(f"Milk: {self.resources['milk']}ml")
        print(f"Coffee: {self.resources['coffee']}g")

    def is_resource_sufficient(self, drink):
        """Returns True when order can be made, False if ingredients are insufficient."""
        can_make = True
        for item in drink.ingredients:
            if drink.ingredients[item] > self.resources[item]:
                print(f"Sorry there is not enough {item}.")
                can_make = False
        return can_make

    def make_coffee(self, order):
        """Deducts the required ingredients from the resources."""
        for item in order.ingredients:
            self.resources[item] -= order.ingredients[item]
        print(f"Here is your {order.name} ☕️. Enjoy!")
#메뉴 클래스
class MenuItem:
    """Models each Menu Item."""
    def __init__(self, name, water, milk, coffee, cost):
        self.name = name
        self.cost = cost
        self.ingredients = {
            "water": water,
            "milk": milk,
            "coffee": coffee
        }


class Menu:
    """Models the Menu with drinks."""
    def __init__(self):
        self.menu = [
            MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
            MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
            MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
        ]

    def get_items(self):
        """Returns all the names of the available menu items"""
        options = ""
        for item in self.menu:
            options += f"{item.name}/"
        return options

    def find_drink(self, order_name):
        """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None"""
        for item in self.menu:
            if item.name == order_name:
                return item
        print("Sorry that item is not available.")
#돈관리 클래스
class MoneyMachine:

    CURRENCY = "$"

    COIN_VALUES = {
        "quarters": 0.25,
        "dimes": 0.10,
        "nickles": 0.05,
        "pennies": 0.01
    }

    def __init__(self):
        self.profit = 0
        self.money_received = 0

    def report(self):
        """Prints the current profit"""
        print(f"Money: {self.CURRENCY}{self.profit}")

    def process_coins(self):
        """Returns the total calculated from coins inserted."""
        print("Please insert coins.")
        for coin in self.COIN_VALUES:
            self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
        return self.money_received

    def make_payment(self, cost):
        """Returns True when payment is accepted, or False if insufficient."""
        self.process_coins()
        if self.money_received >= cost:
            change = round(self.money_received - cost, 2)
            print(f"Here is {self.CURRENCY}{change} in change.")
            self.profit += cost
            self.money_received = 0
            return True
        else:
            print("Sorry that's not enough money. Money refunded.")
            self.money_received = 0
            return False
728x90
반응형

댓글()

Python 인강 Day 11 / Day 100 - 블랙잭 카드게임

개발/파이썬|2023. 3. 16. 20:10
728x90
반응형
#Day 11 = 블랙잭 게임
from random import randint , sample
while True:
    card = [1,2,3,4,5,6,7,8,9,10,10,10,10,11]

    dealer = sample(card, 2)
    player = sample(card, 2)

    sum_player = int(player[0] + player[1])
    sum_dealer = int(dealer[0] + dealer[1])

    print(f"당신의 카드는 {player[0],player[1]} 입니다.")

    add_one = input("카드를 한장 추가 하시려면 y , 아니면 n 을 눌러주세요 > >")

    if sum_dealer <=16:
        sec_dealer = sample(card, 1)
        dealer.append(sec_dealer[0])
        sum_dealer += int(sec_dealer[0])

    if add_one == "y" or add_one == "Y":
    
        sec_player = sample(card,1)
        sum_player += int(sec_player[0] )
        print(f"카드는 {sec_player[0]} 입니다.")
        
        yprint(f"당신의 총점은 {sum_player}")
        print(f"딜러의 카드는 {dealer}")
        print(f"딜러의 총점은 {sum_dealer}")
        
        if sum_dealer >= 21 and sum_player <= 21:
            print("딜러 버스트 당신의 승리입니다.")
        elif sum_player >= 21:
            print("버스트 입니다 , 패배했습니다")
        elif sum_player > sum_dealer:
            print("당신이 승리했습니다!")
        elif sum_player < sum_dealer:
            print("당신이 패배했습니다!")
        else:
            print("동점입니다.")
                        
            
    if add_one == "n" or add_one == "N":
        print(f"당신의 총점은 {sum_player}")
        print(f"딜러의 카드는 {dealer}")
        print(f"딜러의 총점은 {sum_dealer}")
        
        if sum_dealer >= 21 and sum_player <= 21:
            print("딜러 버스트 당신의 승리입니다.")
        elif sum_player >= 21:
            print("버스트 입니다 , 패배했습니다")
        elif sum_player > sum_dealer:
            print("당신이 승리했습니다!")
        elif sum_player < sum_dealer:
            print("당신이 패배했습니다!")
        else:
            print("동점입니다.")
    
    play_again = input("게임을 다시 시작 하시겠습니까?  y 를 누르면 다시시작  or n 을 누르면 종료 > > ")
    if play_again == "n" or play_again == "N":
        break

어찌어찌 동작은하는데 코드가 상당히 복잡해졌다.

def 문으로 함수를 만들어서 리팩토링이 가능할 것 같다.

728x90
반응형

댓글()

Python 인강 Day10 / Day 100

개발/파이썬|2023. 3. 16. 08:56
728x90
반응형

계산기

 

#Day 10 Calculator 

from replit import clear
from art import logo

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}

def calculator():
  print(logo)

  num1 = float(input("What's the first number?: "))
  for symbol in operations:
    print(symbol)
  should_continue = True
 
  while should_continue:
    operation_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
    else:
      should_continue = False
      clear()
      calculator()

calculator()
728x90
반응형

댓글()

유튜브 영상,음원 추출하여 다운받기. 파이썬 코드

개발/파이썬|2023. 3. 14. 17:57
728x90
반응형

실행 결과물

문법 공부만 하다보니 너무 지루하고 힘들어서 chatGPT 의 도움을 받아 코드 작성했다.

from tkinter import *
from tkinter import messagebox
from pytube import YouTube
import glob
import os.path


root = Tk()
root.title("Youtube to mp3")
root.geometry("300x150")
root.resizable(False, False)


def convert():
	par = lnk.get()
	print(par)

	yt = YouTube(par)

	print("start!")
	if(Radiovar.get() == 1):
		print("type: mp4")
		yt.streams.filter().all()
		yt.streams.filter().first().download() 
	else:
		print("type: mp3")
		yt.streams.filter(only_audio=True).all()
		yt.streams.filter(only_audio=True).first().download() 
		print("success")

		files = glob.glob("*.mp4")
		for x in files:
			if not os.path.isdir(x):
				filename = os.path.splitext(x)
				try:
					os.rename(x,filename[0] + '.mp3')
				except:
					pass
	messagebox.showinfo("성공","변경완료") 



lbl = Label(root, text="유튜브 URL 을 아래 폼에 작성해주세요")
lbl.pack()

lnk = Entry(root)
lnk.pack(fill="x")

st = StringVar() 
Radiovar = IntVar() 
Radio_button1 = Radiobutton(text="비디오로 다운받기!",variable=Radiovar,value=1) 
Radio_button2 = Radiobutton(text="음성만 다운받기",variable=Radiovar,value=2)
Radio_button1.pack()
Radio_button2.pack()


btn = Button(root, text="변환",command=convert)
btn.pack()
root.mainloop()

tube.zip
10.43MB

결과물파일 exe 파일이라 압축해놓음

받아서 되네 안되네 해도 수정안해줌 난 잘됨

 

 

728x90
반응형

댓글()