준비
- pyinstaller 설치
pip install pyinstaller
Python 스크립트를 .exe 파일로 변환
다음 명령을 사용하여 스크립트를 .exe 파일로 변환할 수 있습니다.
pyinstaller --onefile --windowed image_crawler.py
- --onefile: 모든 파일을 하나의 실행 파일로 패키징합니다.
- --windowed: 콘솔 창 없이 GUI 애플리케이션으로 실행됩니다.
자세한 예제
- Python 스크립트를 파일로 저장 image_crawler.py 파일을 생성하고 앞서 제공한 코드를 붙여넣습니다.
- PyInstaller 명령 실행 터미널이나 명령 프롬프트를 열고 스크립트가 저장된 디렉터리로 이동합니다. 다음 명령을 실행합니다.
pyinstaller --onefile --windowed image_crawler.py
3. 결과 확인 PyInstaller가 완료되면, dist 디렉터리에 image_crawler.exe 파일이 생성됩니다. 이 파일을 실행하여 프로그 램을 확인할 수 있습니다.
코드 예제
저장할 image_crawler.py 파일의 코드:
import tkinter as tk
from tkinter import filedialog, messagebox
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import requests
import os
import time
import shutil
class ImageCrawlerApp:
def __init__(self, root):
self.root = root
self.root.title("Google Image Crawler")
# 검색어 입력 라벨 및 텍스트 입력 상자
self.label = tk.Label(root, text="검색어:")
self.label.pack()
self.entry = tk.Entry(root, width=50)
self.entry.pack()
# 다운로드 버튼
self.download_button = tk.Button(root, text="이미지 다운로드", command=self.download_images)
self.download_button.pack()
# 저장 경로 선택 버튼
self.path_button = tk.Button(root, text="저장 경로 선택", command=self.select_path)
self.path_button.pack()
# 저장 경로 라벨
self.path_label = tk.Label(root, text="")
self.path_label.pack()
self.download_path = ""
def select_path(self):
self.download_path = filedialog.askdirectory()
self.path_label.config(text=self.download_path)
def download_images(self):
search_query = self.entry.get()
if not search_query:
messagebox.showwarning("입력 오류", "검색어를 입력하세요.")
return
if not self.download_path:
messagebox.showwarning("경로 오류", "저장 경로를 선택하세요.")
return
image_folder_path = os.path.join(self.download_path, search_query)
if os.path.exists(image_folder_path):
answer = messagebox.askyesno("폴더 존재", "이미 해당 폴더가 존재합니다. 삭제할까요?")
if answer:
shutil.rmtree(image_folder_path)
else:
messagebox.showinfo("작업 취소", "작업이 취소되었습니다.")
return
os.makedirs(image_folder_path, exist_ok=True)
# Selenium 설정 (ChromeDriver 경로 설정 필요)
driver_path = 'path/to/chromedriver' # ChromeDriver의 경로로 변경
driver = webdriver.Chrome(executable_path=driver_path)
# 구글 이미지 검색 URL
url = f'https://www.google.com/search?hl=en&tbm=isch&q={search_query}'
# 웹 페이지 열기
driver.get(url)
# 스크롤을 통해 이미지 더 로드하기 (필요 시)
for _ in range(3):
driver.find_element_by_tag_name('body').send_keys(Keys.END)
time.sleep(2)
# 페이지 소스 가져오기
page_source = driver.page_source
# BeautifulSoup을 사용하여 HTML 파싱
soup = BeautifulSoup(page_source, 'html.parser')
# 이미지 URL 추출 (필터링 적용)
image_elements = soup.find_all('img')
image_urls = []
for img in image_elements:
src = img.get('data-src') or img.get('src')
if src and 'http' in src and not any(kw in src for kw in ['logo', 'favicon']):
image_urls.append(src)
# 이미지 다운로드
for i, img_url in enumerate(image_urls):
try:
img_data = requests.get(img_url).content
with open(os.path.join(image_folder_path, f'image_{i+1}.jpg'), 'wb') as handler:
handler.write(img_data)
except Exception as e:
print(f'Failed to download {img_url}: {e}')
# 드라이버 종료
driver.quit()
messagebox.showinfo("완료", f'{len(image_urls)}개의 이미지를 다운로드했습니다.')
if __name__ == "__main__":
root = tk.Tk()
app = ImageCrawlerApp(root)
root.mainloop()
이 과정을 통해 Python 스크립트를 단일 실행 파일로 만들 수 있으며, 다른 시스템에서도 Python 환경 없이 실행할 수 있습니다.