수정중

This commit is contained in:
9700X_PC 2024-11-12 16:57:45 +09:00
parent 48f5d4ff54
commit 0dca9937ef
24 changed files with 150 additions and 250 deletions

View File

@ -1,4 +1,4 @@
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QDialog from PySide6.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QDialog
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
import sqlite3 import sqlite3
import sys import sys
@ -12,6 +12,7 @@ class ProductViewer(QWidget):
self.product_index = 0 self.product_index = 0
self.products = self.load_products() self.products = self.load_products()
self.total_products = len(self.products) self.total_products = len(self.products)
self.resize(600, 680) # 윈도우 크기를 고정 (1024x768)
# UI 초기화 # UI 초기화
self.init_ui() self.init_ui()
@ -27,23 +28,27 @@ class ProductViewer(QWidget):
# 중간 레이아웃에 여러 개의 SearchResultCard를 추가 # 중간 레이아웃에 여러 개의 SearchResultCard를 추가
self.middle_layout = QHBoxLayout() self.middle_layout = QHBoxLayout()
self.search_result_cards = [SearchResultCard(i+1) for i in range(5)] self.search_result_cards = [SearchResultCard(i+1) for i in range(4)]
for card in self.search_result_cards: for card in self.search_result_cards:
self.middle_layout.addWidget(card) self.middle_layout.addWidget(card, 2)
# card.setFixedHeight(300) # 각 카드의 크기를 고정
main_layout.addLayout(self.middle_layout) main_layout.addLayout(self.middle_layout)
# 하단 레이아웃 # 하단 레이아웃
self.bottom_layout = QHBoxLayout() self.bottom_layout = QHBoxLayout()
self.left_button = QPushButton("") self.left_button = QPushButton("")
self.left_button.setFixedSize(200,30)
self.left_button.clicked.connect(self.previous_product) self.left_button.clicked.connect(self.previous_product)
self.page_button = QPushButton(f"{self.product_index + 1}/{self.total_products}") self.page_button = QPushButton(f"{self.product_index + 1}/{self.total_products}")
self.page_button.setFixedSize(150,30)
self.page_button.clicked.connect(self.show_product_dialog) self.page_button.clicked.connect(self.show_product_dialog)
self.right_button = QPushButton("") self.right_button = QPushButton("")
self.right_button.setFixedSize(200,30)
self.right_button.clicked.connect(self.next_product) self.right_button.clicked.connect(self.next_product)
self.bottom_layout.addWidget(self.left_button) self.bottom_layout.addWidget(self.left_button, 3)
self.bottom_layout.addWidget(self.page_button) self.bottom_layout.addWidget(self.page_button, 1)
self.bottom_layout.addWidget(self.right_button) self.bottom_layout.addWidget(self.right_button, 3)
main_layout.addLayout(self.bottom_layout) main_layout.addLayout(self.bottom_layout)
self.setLayout(main_layout) self.setLayout(main_layout)
@ -59,33 +64,29 @@ class ProductViewer(QWidget):
# 현재 상품 데이터를 로드하여 ProductCard에 설정 # 현재 상품 데이터를 로드하여 ProductCard에 설정
product = self.products[self.product_index] product = self.products[self.product_index]
product_name = product[1] product_name = product[1]
product_price = product[4]
product_img_url = product[2] product_img_url = product[2]
self.product_card.set_data(name=product_name, price=product_price, img_url=product_img_url) product_tag = product[3]
print(f"product : {product}") product_price = product[4]
print(f"product_name : {product_name}") product_cat = product[5]
print(f"product_price : {product_price}")
print(f"product_img_url : {product_img_url}") self.product_card.set_data(name=product_name, price=product_price, tag=product_tag, cat=product_cat, img_url=product_img_url)
# SearchResultCard 초기화 및 데이터 로드 # SearchResultCard 초기화 및 데이터 로드
self.reset_search_result_cards() # 이전 카드 데이터 리셋 self.reset_search_result_cards() # 이전 카드 데이터 리셋
search_results = self.load_search_results(product[0]) search_results = self.load_search_results(product[0])
print(f"search_results : {search_results}")
for i, result in enumerate(search_results): for i, result in enumerate(search_results):
if i < len(self.search_result_cards): if i < len(self.search_result_cards):
title = result[1] title = result[1]
print(f"{i}번째 title : {title}")
price = result[3] price = result[3]
print(f"{i}번째 price : {price}")
source = result[2] source = result[2]
print(f"{i}번째 source : {source}")
img_url = result[4] img_url = result[4]
print(f"{i}번째 img_url : {img_url}") is_selected = result[5] # DB에서 is_selected 값을 가져옴
self.search_result_cards[i].set_data(name=title, price=price, source=source, img_url=img_url) self.search_result_cards[i].set_data(name=title, price=price, source=source, img_url=img_url, is_selected=is_selected, cursor=self.cursor)
# 페이지 버튼 텍스트 업데이트 # 페이지 버튼 텍스트 업데이트
self.page_button.setText(f"{self.product_index + 1}/{self.total_products}") self.page_button.setText(f"{self.product_index + 1}/{self.total_products}")
def reset_search_result_cards(self): def reset_search_result_cards(self):
# 각 SearchResultCard를 초기화 # 각 SearchResultCard를 초기화
for card in self.search_result_cards: for card in self.search_result_cards:
@ -93,9 +94,8 @@ class ProductViewer(QWidget):
def load_search_results(self, product_id): def load_search_results(self, product_id):
# DB에서 search_results 테이블의 데이터를 로드 # DB에서 search_results 테이블의 데이터를 로드
cursor = self.conn.cursor() self.cursor.execute("SELECT * FROM search_results WHERE product_id=?", (product_id,))
cursor.execute("SELECT * FROM search_results WHERE product_id=?", (product_id,)) return self.cursor.fetchall()
return cursor.fetchall()
def previous_product(self): def previous_product(self):
if self.product_index > 0: if self.product_index > 0:
@ -127,7 +127,7 @@ class ProductViewer(QWidget):
elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
self.show_product_dialog() self.show_product_dialog()
def select_card(self, index): def select_card(self, index, cursor):
# 선택된 카드의 UI 갱신 및 데이터베이스 업데이트 # 선택된 카드의 UI 갱신 및 데이터베이스 업데이트
for i, card in enumerate(self.search_result_cards): for i, card in enumerate(self.search_result_cards):
if i == index: if i == index:

View File

@ -36,13 +36,17 @@ class BaiduImageSearcher:
}) })
self.initial_url = 'https://graph.baidu.com/pcpage/index?tpl_from=pc' self.initial_url = 'https://graph.baidu.com/pcpage/index?tpl_from=pc'
upload_button_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/span[1]/span[1]' # upload_button_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/span[1]/span[1]'
self.logger.info("goto URL") self.logger.info("goto URL")
# self.page.route("**/*", lambda route, request: route.abort() if request.resource_type in ["image", "stylesheet", "font"] else route.continue_()) # self.page.route("**/*", lambda route, request: route.abort() if request.resource_type in ["image", "stylesheet", "font"] else route.continue_())
# # self.page.goto(self.initial_url) # 최초 접속 URL
# self.goto_initialPage()
# self.page.wait_for_selector(upload_button_xpath)
def goto_initialPage(self):
self.page.goto(self.initial_url) # 최초 접속 URL self.page.goto(self.initial_url) # 최초 접속 URL
self.page.wait_for_selector(upload_button_xpath)
def close_browser(self): def close_browser(self):
# 브라우저 종료 # 브라우저 종료
@ -77,15 +81,18 @@ class BaiduImageSearcher:
# 첫 번째 검색과 이후 검색의 선택자를 다르게 설정 # 첫 번째 검색과 이후 검색의 선택자를 다르게 설정
# if self.is_first_search: # if self.is_first_search:
if self.is_first_search: # if self.is_first_search:
self.logger.info("is_first_search") # self.logger.info("is_first_search")
upload_button_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/span[1]/span[1]' # upload_button_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/span[1]/span[1]'
upload_input_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/div/div[2]/div[2]/div/form/input' # upload_input_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/div/div[2]/div[2]/div/form/input'
self.is_first_search = False # 이후 검색에서는 일반 선택자를 사용 # # self.is_first_search = False # 이후 검색에서는 일반 선택자를 사용
else: # else:
self.logger.info("another search") # self.logger.info("another search")
upload_button_xpath = '//*[@id="app"]/div/div[1]/div/div[1]/div/div/div[1]/span[1]/span[1]' # upload_button_xpath = '//*[@id="app"]/div/div[1]/div/div[1]/div/div/div[1]/span[1]/span[1]'
upload_input_xpath = '//*[@id="app"]/div/div[1]/div/div[1]/div/div/div[1]/div/div[2]/div[2]/div/form/input' # upload_input_xpath = '//*[@id="app"]/div/div[1]/div/div[1]/div/div/div[1]/div/div[2]/div[2]/div/form/input'
upload_button_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/span[1]/span[1]'
upload_input_xpath = '//*[@id="app"]/div/div[1]/div[7]/div/div/div[2]/div[2]/div/form/input'
# 이미지 업로드 버튼 클릭 및 파일 업로드 # 이미지 업로드 버튼 클릭 및 파일 업로드
self.page.wait_for_selector(upload_button_xpath) self.page.wait_for_selector(upload_button_xpath)
@ -129,7 +136,9 @@ class BaiduImageSearcher:
content = None content = None
self.logger.info("검색 결과 페이지에서 JSON 데이터 추출") self.logger.info("검색 결과 페이지에서 JSON 데이터 추출")
content = self.page.content() content = self.page.content()
self.page.go_back() # 뒤로 가기
soup = BeautifulSoup(content, 'html.parser') soup = BeautifulSoup(content, 'html.parser')
script_tag = soup.select_one("html > head > script:nth-of-type(2)") script_tag = soup.select_one("html > head > script:nth-of-type(2)")
@ -167,8 +176,7 @@ class BaiduImageSearcher:
"original_url": original_url "original_url": original_url
}) })
self.logger.info("product_info 추출 완료") self.logger.info("product_info 추출 완료")
self.logger.info(f"{product_info}") self.logger.info(f"추출된 정보 \n{product_info}")
input("로그를 확인한 후 아무 키나 눌러서 계속하세요...")
return product_info return product_info
except json.JSONDecodeError as e: except json.JSONDecodeError as e:

View File

@ -63,6 +63,9 @@ class MainProcessor:
while attempt < max_retries: while attempt < max_retries:
# upload_image 메서드 실행 및 성공 여부 확인 # upload_image 메서드 실행 및 성공 여부 확인
self.image_searcher.goto_initialPage()
self.logger.debug(f"검색페이지로 가기")
is_success_upload_image = self.image_searcher.upload_image(image_path) is_success_upload_image = self.image_searcher.upload_image(image_path)
if not is_success_upload_image: if not is_success_upload_image:
attempt += 1 attempt += 1
@ -80,14 +83,14 @@ class MainProcessor:
# 검색 결과 추출 # 검색 결과 추출
search_results = self.image_searcher.extract_product_data() search_results = self.image_searcher.extract_product_data()
if not search_results: # if search_results == []: # 빈 리스트일 경우만 실패로 간주
attempt += 1 # attempt += 1
self.logger.warning(f"Extract product data failed for Product ID [{product_id}]. Retry {attempt}/{max_retries}") # self.logger.warning(f"Extract product data failed for Product ID [{product_id}]. Retry {attempt}/{max_retries}")
time.sleep(1) # time.sleep(1)
continue # 재시도 시 루프를 다시 시작 # continue # 재시도 시 루프를 다시 시작
# 모든 작업이 성공하면 루프 종료 # 모든 작업이 성공하면 루프 종료
if is_success_upload_image and is_success_expand_results and search_results: if is_success_upload_image and is_success_expand_results:
break break
else: else:
# 재시도 횟수 초과 시 경고 로그 출력 및 다음 제품으로 이동 # 재시도 횟수 초과 시 경고 로그 출력 및 다음 제품으로 이동
@ -95,6 +98,8 @@ class MainProcessor:
continue continue
# 성공 시 검색 결과를 DB에 저장 # 성공 시 검색 결과를 DB에 저장
self.logger.debug(f"Insert DB: {product_id}")
self.db_manager.insert_search_results(product_id, search_results) self.db_manager.insert_search_results(product_id, search_results)
os.remove(image_path) os.remove(image_path)

View File

@ -1,55 +1,82 @@
from PySide6.QtWidgets import QWidget, QGridLayout, QLabel from PySide6.QtWidgets import QWidget, QVBoxLayout, QGridLayout, QLabel
from PySide6.QtGui import QPixmap from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
import requests import requests
class ProductCard(QWidget): class ProductCard(QWidget):
def __init__(self, index=1): def __init__(self):
super().__init__() super().__init__()
self.setFixedSize(220, 300) # self.setFixedSize(800, 300)
self.layout = QGridLayout(self)
# 외부 위젯으로 감싸서 테두리 적용
container_widget = QWidget(self)
container_layout = QVBoxLayout(container_widget)
self.layout = QGridLayout()
# 테두리 스타일 적용
container_widget.setStyleSheet("border: 2px solid black;")
# UI 요소 초기화 # UI 요소 초기화
self.index_label = QLabel(str(index)) self.info1_label = QLabel('검색 상품')
self.index_label.setAlignment(Qt.AlignCenter) self.info1_label.setAlignment(Qt.AlignCenter)
self.index_label.setStyleSheet("font-weight: bold; font-size: 16px;") self.info1_label.setStyleSheet("font-weight: bold; font-size: 16px;")
self.info2_label = QLabel('상품 정보')
self.info2_label.setAlignment(Qt.AlignCenter)
self.info2_label.setStyleSheet("font-weight: bold; font-size: 16px;")
self.image_label = QLabel() self.image_label = QLabel()
self.image_label.setFixedSize(200, 140) self.image_label.setFixedSize(250, 250)
self.name_label = QLabel("상품명:") self.name_label = QLabel("상품명:")
self.name_value = QLabel("") self.name_value = QLabel("")
self.name_value.setWordWrap(True)
self.name_value.setFixedSize(120, 50)
self.price_label = QLabel("가격:") self.price_label = QLabel("가격:")
self.price_value = QLabel("") self.price_value = QLabel("")
self.select_label = QLabel("미선택") self.tag_label = QLabel("태그:")
self.select_label.setAlignment(Qt.AlignCenter) self.tag_value = QLabel("")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
# 레이아웃 구성 self.cat_label = QLabel("카테고리:")
self.layout.addWidget(self.index_label, 0, 0, 1, 2) self.cat_value = QLabel("")
self.layout.addWidget(self.image_label, 1, 0, 1, 2)
self.layout.addWidget(self.name_label, 2, 0) # 그리드 레이아웃 구성
self.layout.addWidget(self.name_value, 2, 1) self.layout.addWidget(self.info1_label, 0, 0, 1, 1)
self.layout.addWidget(self.price_label, 3, 0) self.layout.addWidget(self.info2_label, 0, 1, 1, 4)
self.layout.addWidget(self.price_value, 3, 1) self.layout.addWidget(self.image_label, 1, 0, 4, 1)
self.layout.addWidget(self.select_label, 4, 0, 1, 2)
# 각 정보 라벨과 값 배치
self.layout.addWidget(self.name_label, 1, 2, 1, 1)
self.layout.addWidget(self.name_value, 1, 3, 1, 1)
self.layout.addWidget(self.price_label, 2, 2, 1, 1)
self.layout.addWidget(self.price_value, 2, 3, 1, 1)
self.layout.addWidget(self.tag_label, 3, 2, 1, 1)
self.layout.addWidget(self.tag_value, 3, 3, 1, 1)
self.layout.addWidget(self.cat_label, 4, 2, 1, 1)
self.layout.addWidget(self.cat_value, 4, 3, 1, 1)
container_layout.addLayout(self.layout)
def reset(self): def reset(self):
"""카드의 데이터를 초기화합니다.""" """카드의 데이터를 초기화합니다."""
self.name_value.setText("") self.name_value.setText("")
self.price_value.setText("") self.price_value.setText("")
self.tag_value.setText("")
self.cat_value.setText("")
self.image_label.clear() self.image_label.clear()
self.set_selected(False)
def set_data(self, name, price, img_url): def set_data(self, name, price, tag, cat, img_url):
"""카드에 상품 데이터를 설정합니다.""" """카드에 상품 데이터를 설정합니다."""
self.name_value.setText(name) self.name_value.setText(name)
self.price_value.setText(str(price)) # self.price_value.setText(str(price))
self.price_value.setText(f"{price:,}")
self.tag_value.setText(tag)
self.cat_value.setText(cat)
# self.price_value.setText(str(price))
# 이미지 설정 # 이미지 설정
pixmap = QPixmap() pixmap = QPixmap()
@ -69,99 +96,3 @@ class ProductCard(QWidget):
except Exception as e: except Exception as e:
print(f"Image download error: {e}") print(f"Image download error: {e}")
return None return None
def set_selected(self, selected):
"""카드의 선택 상태를 설정합니다."""
if selected:
self.select_label.setText("선택")
self.select_label.setStyleSheet("font-weight: bold; color: red;")
self.setStyleSheet("border: 2px solid red;")
else:
self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;")
class SearchResultCard(QWidget):
def __init__(self, index=1):
super().__init__()
self.setFixedSize(220, 300)
self.layout = QGridLayout(self)
# UI 요소 초기화
self.index_label = QLabel(str(index))
self.index_label.setAlignment(Qt.AlignCenter)
self.index_label.setStyleSheet("font-weight: bold; font-size: 16px;")
self.image_label = QLabel()
self.image_label.setFixedSize(200, 140)
self.name_label = QLabel("상품명:")
self.name_value = QLabel("")
self.name_value.setWordWrap(True)
self.name_value.setFixedSize(120, 50)
self.price_label = QLabel("가격:")
self.price_value = QLabel("")
self.source_label = QLabel("출처:")
self.source_value = QLabel("")
self.select_label = QLabel("미선택")
self.select_label.setAlignment(Qt.AlignCenter)
self.select_label.setStyleSheet("font-weight: bold; color: black;")
# 레이아웃 구성
self.layout.addWidget(self.index_label, 0, 0, 1, 2)
self.layout.addWidget(self.image_label, 1, 0, 1, 2)
self.layout.addWidget(self.name_label, 2, 0)
self.layout.addWidget(self.name_value, 2, 1)
self.layout.addWidget(self.price_label, 3, 0)
self.layout.addWidget(self.price_value, 3, 1)
self.layout.addWidget(self.source_label, 4, 0)
self.layout.addWidget(self.source_value, 4, 1)
self.layout.addWidget(self.select_label, 5, 0, 1, 2)
def reset(self):
"""카드의 데이터를 초기화합니다."""
self.name_value.setText("")
self.price_value.setText("")
self.source_value.setText("")
self.image_label.clear()
self.set_selected(False)
def set_data(self, name, price, source, img_url):
"""카드에 검색 결과 데이터를 설정합니다."""
self.name_value.setText(name)
self.price_value.setText(price)
self.source_value.setText(source)
# 이미지 설정
pixmap = QPixmap()
img_data = self.download_image_data(img_url)
if img_data:
pixmap.loadFromData(img_data)
self.image_label.setPixmap(pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio))
else:
self.image_label.clear()
def download_image_data(self, img_url):
"""이미지 URL에서 데이터를 다운로드합니다."""
try:
response = requests.get(img_url)
if response.status_code == 200:
return response.content
except Exception as e:
print(f"Image download error: {e}")
return None
def set_selected(self, selected):
"""카드의 선택 상태를 설정합니다."""
if selected:
self.select_label.setText("선택")
self.select_label.setStyleSheet("font-weight: bold; color: red;")
self.setStyleSheet("border: 2px solid red;")
else:
self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;")

BIN
products.db Normal file

Binary file not shown.

View File

@ -3,89 +3,10 @@ from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
import requests import requests
class ProductCard(QWidget):
def __init__(self, index=1):
super().__init__()
self.setFixedSize(220, 300)
self.layout = QGridLayout(self)
# UI 요소 초기화
self.index_label = QLabel(str(index))
self.index_label.setAlignment(Qt.AlignCenter)
self.index_label.setStyleSheet("font-weight: bold; font-size: 16px;")
self.image_label = QLabel()
self.image_label.setFixedSize(200, 140)
self.name_label = QLabel("상품명:")
self.name_value = QLabel("")
self.name_value.setWordWrap(True)
self.name_value.setFixedSize(120, 50)
self.price_label = QLabel("가격:")
self.price_value = QLabel("")
self.select_label = QLabel("미선택")
self.select_label.setAlignment(Qt.AlignCenter)
self.select_label.setStyleSheet("font-weight: bold; color: black;")
# 레이아웃 구성
self.layout.addWidget(self.index_label, 0, 0, 1, 2)
self.layout.addWidget(self.image_label, 1, 0, 1, 2)
self.layout.addWidget(self.name_label, 2, 0)
self.layout.addWidget(self.name_value, 2, 1)
self.layout.addWidget(self.price_label, 3, 0)
self.layout.addWidget(self.price_value, 3, 1)
self.layout.addWidget(self.select_label, 4, 0, 1, 2)
def reset(self):
"""카드의 데이터를 초기화합니다."""
self.name_value.setText("")
self.price_value.setText("")
self.image_label.clear()
self.set_selected(False)
def set_data(self, name, price, img_url):
"""카드에 상품 데이터를 설정합니다."""
self.name_value.setText(name)
self.price_value.setText(price)
# 이미지 설정
pixmap = QPixmap()
img_data = self.download_image_data(img_url)
if img_data:
pixmap.loadFromData(img_data)
self.image_label.setPixmap(pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio))
else:
self.image_label.clear()
def download_image_data(self, img_url):
"""이미지 URL에서 데이터를 다운로드합니다."""
try:
response = requests.get(img_url)
if response.status_code == 200:
return response.content
except Exception as e:
print(f"Image download error: {e}")
return None
def set_selected(self, selected):
"""카드의 선택 상태를 설정합니다."""
if selected:
self.select_label.setText("선택")
self.select_label.setStyleSheet("font-weight: bold; color: red;")
self.setStyleSheet("border: 2px solid red;")
else:
self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;")
class SearchResultCard(QWidget): class SearchResultCard(QWidget):
def __init__(self, index=1): def __init__(self, index=1):
super().__init__() super().__init__()
self.setFixedSize(220, 300) self.setFixedSize(160, 300)
self.layout = QGridLayout(self) self.layout = QGridLayout(self)
# UI 요소 초기화 # UI 요소 초기화
@ -94,12 +15,14 @@ class SearchResultCard(QWidget):
self.index_label.setStyleSheet("font-weight: bold; font-size: 16px;") self.index_label.setStyleSheet("font-weight: bold; font-size: 16px;")
self.image_label = QLabel() self.image_label = QLabel()
self.image_label.setFixedSize(200, 140) # self.image_label.setFixedSize(140, 120)
self.image_label.setFixedHeight(120)
self.name_label = QLabel("상품명:") self.name_label = QLabel("상품명:")
self.name_value = QLabel("") self.name_value = QLabel("")
self.name_value.setWordWrap(True) self.name_value.setWordWrap(True)
self.name_value.setFixedSize(120, 50) # self.name_value.setFixedSize(120, 50)
self.name_value.setFixedHeight(50)
self.price_label = QLabel("가격:") self.price_label = QLabel("가격:")
self.price_value = QLabel("") self.price_value = QLabel("")
@ -128,12 +51,12 @@ class SearchResultCard(QWidget):
self.price_value.setText("") self.price_value.setText("")
self.source_value.setText("") self.source_value.setText("")
self.image_label.clear() self.image_label.clear()
self.set_selected(False) self.set_selected(False, None) # 기본 선택 해제 상태로 초기화
def set_data(self, name, price, source, img_url): def set_data(self, name, price, source, img_url, is_selected, cursor):
"""카드에 검색 결과 데이터를 설정합니다.""" """카드에 검색 결과 데이터를 설정하고 선택 상태를 적용합니다."""
self.name_value.setText(name) self.name_value.setText(name)
self.price_value.setText(price) self.price_value.setText(f"{price}")
self.source_value.setText(source) self.source_value.setText(source)
# 이미지 설정 # 이미지 설정
@ -145,6 +68,9 @@ class SearchResultCard(QWidget):
else: else:
self.image_label.clear() self.image_label.clear()
# 선택 상태에 따라 UI 업데이트
self.set_selected(is_selected, cursor)
def download_image_data(self, img_url): def download_image_data(self, img_url):
"""이미지 URL에서 데이터를 다운로드합니다.""" """이미지 URL에서 데이터를 다운로드합니다."""
try: try:
@ -155,8 +81,9 @@ class SearchResultCard(QWidget):
print(f"Image download error: {e}") print(f"Image download error: {e}")
return None return None
def set_selected(self, selected): def set_selected(self, selected, cursor):
"""카드의 선택 상태를 설정합니다.""" """카드의 선택 상태를 설정하고 데이터베이스를 업데이트합니다."""
# 선택 상태에 따라 스타일 및 텍스트 변경
if selected: if selected:
self.select_label.setText("선택") self.select_label.setText("선택")
self.select_label.setStyleSheet("font-weight: bold; color: red;") self.select_label.setStyleSheet("font-weight: bold; color: red;")
@ -165,3 +92,11 @@ class SearchResultCard(QWidget):
self.select_label.setText("미선택") self.select_label.setText("미선택")
self.select_label.setStyleSheet("font-weight: bold; color: black;") self.select_label.setStyleSheet("font-weight: bold; color: black;")
self.setStyleSheet("border: 1px solid grey;") self.setStyleSheet("border: 1px solid grey;")
# 데이터베이스에 선택 상태 업데이트
if cursor is not None:
try:
cursor.execute("UPDATE search_results SET is_selected = ? WHERE id = ?", (1 if selected else 0, self.index))
cursor.connection.commit() # 변경 사항 커밋
except Exception as e:
print(f"Error updating selection in database: {e}")

BIN
temp/1.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 970 KiB

BIN
temp/13.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View File

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

BIN
temp/31.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 970 KiB

BIN
temp/32.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

BIN
temp/33.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

BIN
temp/34.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

BIN
temp/35.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 KiB

BIN
temp/36.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

BIN
temp/37.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

BIN
temp/38.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

BIN
temp/39.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

BIN
temp/40.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

0
temp/41.jpg Normal file
View File

20
test/db_del.py Normal file
View File

@ -0,0 +1,20 @@
import sqlite3
def delete_rows_from_products():
# 데이터베이스 연결
conn = sqlite3.connect("products.db")
cursor = conn.cursor()
try:
# id가 1부터 40까지인 행 삭제
cursor.execute("DELETE FROM search_results WHERE product_id BETWEEN 11 AND 11")
conn.commit() # 변경 사항 저장
print("1행부터 40행까지 삭제 완료.")
except sqlite3.Error as e:
print("데이터 삭제 중 오류 발생:", e)
finally:
# 데이터베이스 연결 종료
conn.close()
# 함수 호출
delete_rows_from_products()

View File

@ -92,6 +92,7 @@ with sync_playwright() as p:
url = "https://graph.baidu.com/pcpage/index?tpl_from=pc" url = "https://graph.baidu.com/pcpage/index?tpl_from=pc"
page.goto(url) page.goto(url)
for file_name in file_list: for file_name in file_list:
print(f"{file_name} 처리 중...") print(f"{file_name} 처리 중...")
process_image(page, file_name) process_image(page, file_name)