타오파서 대폭수정.
This commit is contained in:
parent
844366938d
commit
06c01c6d90
|
|
@ -95,7 +95,6 @@ def automatch(db, item_count, message_controller, sort_order, progress_callback=
|
|||
for i, product in enumerate(products):
|
||||
logger.debug(f"{i}번째 product 정보 DB 업데이트 준비")
|
||||
itemUrl, itemID, imageUrl, item_name, price, sales_volume = product
|
||||
|
||||
# DB에 상품 정보 업데이트
|
||||
update_query = """
|
||||
INSERT INTO Taobao (keyword_id, itemUrl, itemID, imageUrl, item_name, price, sales_volume)
|
||||
|
|
@ -105,7 +104,7 @@ def automatch(db, item_count, message_controller, sort_order, progress_callback=
|
|||
cursor.execute(update_query, (keyword_id, itemUrl, itemID, imageUrl, item_name, price, sales_volume))
|
||||
logger.debug(f"TaoBao 테이블에 [{product}/{len(products)}] 내용 업데이트 실행")
|
||||
except Exception as e:
|
||||
logger.debug(f"product 정보 DB 업데이트 중 오류 발생 : {e}")
|
||||
logger.debug(f"product 정보 DB 업데이트 중 오류 발생 : {e}", exc_info=True)
|
||||
|
||||
logger.debug(f"{len(products)}개의 product 정보 DB 업데이트 완료")
|
||||
|
||||
|
|
@ -120,7 +119,19 @@ def automatch(db, item_count, message_controller, sort_order, progress_callback=
|
|||
# for index, (row, product) in enumerate(zip(group.iterrows(), products[:product_count])):
|
||||
for index, (row, product) in enumerate(zip(group.itertuples(index=False), products[:product_count])):
|
||||
|
||||
itemUrl, itemID, imageUrl, item_name, price, sales_volume = product
|
||||
# itemUrl, itemID, imageUrl, item_name, price, sales_volume = product # 튜플일때
|
||||
|
||||
# 상품 정보 추출 #리스트일때
|
||||
itemUrl = product['Product URL']
|
||||
itemID = product['Tao_itemID']
|
||||
imageUrl = product['Image URL']
|
||||
item_name = product['Product Name']
|
||||
price = product['Price']
|
||||
sales_volume = product['Sales Volume']
|
||||
|
||||
if price == '' and itemID =='':
|
||||
continue
|
||||
|
||||
if keyword_id != row.keyword_id:
|
||||
continue
|
||||
|
||||
|
|
@ -154,7 +165,7 @@ def automatch(db, item_count, message_controller, sort_order, progress_callback=
|
|||
# PC 주소 생성
|
||||
match = re.search(r'taobao.com/i(\d{10,12})', itemUrl)
|
||||
pc_url = f"https://item.taobao.com/item.htm?id={match.group(1)}" if match else ""
|
||||
|
||||
|
||||
# NaverShopping 테이블에 매칭 정보 업데이트
|
||||
update_ns_query = """
|
||||
UPDATE NaverShopping
|
||||
|
|
|
|||
|
|
@ -37,30 +37,25 @@ def load_cookies(driver):
|
|||
logger.debug(f"쿠키 로드 중 기타 에러 발생 : {e}")
|
||||
return False
|
||||
|
||||
def check_login_status_ori(driver):
|
||||
# 로그인되지 않은 상태의 XPath
|
||||
not_logged_in_xpath = "//li[@id='J_SiteNavLogin']/div/div/a"
|
||||
# 로그인된 상태의 XPath
|
||||
# logged_in_xpath = "//li[@id='J_SiteNavLogin']/div/div[2]/a"
|
||||
def check_login_status_by_iframe(driver):
|
||||
logged_in_xpath = "/html/body/div[1]/div/ul[1]/li[2]/div[1]/div[2]/a"
|
||||
|
||||
# # 로그인되지 않은 상태 확인
|
||||
# if WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, not_logged_in_xpath))):
|
||||
# logger.debug("로그인되지 않았습니다. 로그인이 필요합니다.")
|
||||
# return False
|
||||
logger.debug("로그인된 상태 확인")
|
||||
# 로그인된 상태 확인
|
||||
if WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, logged_in_xpath))):
|
||||
user_id_text = driver.find_element(By.XPATH, logged_in_xpath).text
|
||||
logger.debug(f"로그인된 상태입니다. 로그인된 ID: {user_id_text}")
|
||||
return True
|
||||
# 로그인되지 않은 상태 확인
|
||||
elif WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, not_logged_in_xpath))):
|
||||
logger.debug("로그인되지 않았습니다. 로그인이 필요합니다.")
|
||||
return False
|
||||
else:
|
||||
logger.debug("로그인 상태를 확인할 수 없습니다.")
|
||||
return False
|
||||
while True:
|
||||
try:
|
||||
logger.debug("로그인된 상태 확인 중...")
|
||||
# 로그인된 상태 확인
|
||||
if driver.find_element(By.XPATH, logged_in_xpath):
|
||||
user_id_text = driver.find_element(By.XPATH, logged_in_xpath).text
|
||||
logger.debug(f"로그인된 상태입니다. 로그인된 ID: {user_id_text}")
|
||||
return True
|
||||
except:
|
||||
# 로그인되지 않은 상태 확인
|
||||
try:
|
||||
logger.debug("로그인되지 않았습니다. 로그인이 필요합니다.")
|
||||
time.sleep(5) # 5초 후 다시 체크
|
||||
except:
|
||||
logger.debug("로그인 상태를 확인할 수 없습니다. 잠시 후 다시 시도합니다.")
|
||||
time.sleep(5) # 예외 발생 시 5초 대기 후 재시도
|
||||
|
||||
|
||||
def check_login_status(driver):
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -32,6 +32,6 @@ class TaoScrapingThread(QThread):
|
|||
|
||||
logger.debug("Automatch 작업 완료")
|
||||
except Exception as e:
|
||||
logger.error(f"Automatch 스레드에서 오류 발생: {e}")
|
||||
logger.error(f"Automatch 스레드에서 오류 발생: {e}", exc_info=True)
|
||||
finally:
|
||||
self.finished.emit()
|
||||
114
taoseller.py
114
taoseller.py
|
|
@ -81,7 +81,7 @@ def update_db(db_name, query, params):
|
|||
conn.commit()
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"Failed to update database: {e}")
|
||||
print(f"Failed to update database: {e}", exc_info=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
@ -174,7 +174,7 @@ class PandasModel(QAbstractTableModel):
|
|||
self._data.reset_index(drop=True, inplace=True)
|
||||
self.layoutChanged.emit()
|
||||
except Exception as e:
|
||||
print(f"Error sorting data: {e}")
|
||||
print(f"Error sorting data: {e}", exc_info=True)
|
||||
|
||||
def setData(self, index, value, role=Qt.EditRole):
|
||||
if not index.isValid():
|
||||
|
|
@ -233,7 +233,7 @@ class PandasModel(QAbstractTableModel):
|
|||
connection.commit()
|
||||
except Exception as e:
|
||||
connection.rollback()
|
||||
print(f"Failed to update database: {e}")
|
||||
print(f"Failed to update database: {e}", exc_info=True)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
|
@ -567,7 +567,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.automatch_thread.finished.connect(self.on_automatch_finished) # automatch 작업 완료 후 처리
|
||||
self.automatch_thread.start()
|
||||
except Exception as e:
|
||||
logger.debug(f"타오바오 자동매칭 스레드 실행 중 에러 : {e}")
|
||||
logger.debug(f"타오바오 자동매칭 스레드 실행 중 에러 : {e}", exc_info=True)
|
||||
|
||||
def on_automatch_finished(self):
|
||||
# automatch 작업 완료 후 처리
|
||||
|
|
@ -841,7 +841,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
conn.close()
|
||||
return count
|
||||
except Exception as e:
|
||||
logger.debug(f"Error: {e}")
|
||||
logger.debug(f"Error: {e}", exc_info=True)
|
||||
return 0 # 에러가 발생한 경우 0 반환
|
||||
|
||||
|
||||
|
|
@ -1032,35 +1032,46 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
|
||||
|
||||
def save_to_excel_with_xlwings_by_branch(self, db_name, file_name):
|
||||
# 로그 다이얼로그 생성 및 표시
|
||||
log_dialog = LogDialog()
|
||||
log_dialog.show()
|
||||
self.saved_files = []
|
||||
|
||||
logger.debug("엑셀 저장 로그기록 시작")
|
||||
message = "엑셀 저장 로그기록 시작"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
try:
|
||||
# 로그 다이얼로그 생성 및 표시
|
||||
log_dialog = LogDialog()
|
||||
log_dialog.show()
|
||||
self.saved_files = []
|
||||
|
||||
logger.debug("엑셀 저장 로그기록 시작")
|
||||
message = "엑셀 저장 로그기록 시작"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
|
||||
# 로그 설정
|
||||
logger.debug("엑셀 저장 로그기록 파일 생성")
|
||||
|
||||
# 데이터베이스에서 필요한 데이터 로드
|
||||
conn = sqlite3.connect(db_name)
|
||||
query = "SELECT MatchingUrl, keyword, MatchingCat, delvFee, packingFee, plusFee, manuTag, merged_price FROM NaverShopping WHERE MatchingUrl IS NOT NULL"
|
||||
df = pd.read_sql_query(query, conn)
|
||||
conn.close()
|
||||
logger.debug("DB 읽기 완료")
|
||||
message = "DB 읽기 완료"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
# 'manuTag' 필드에서 '오늘' 단어 제거
|
||||
df['manuTag'] = df['manuTag'].apply(lambda x: ','.join([word for word in str(x).split(',') if '오늘' not in word.strip()]))
|
||||
logger.debug("태그 필터링")
|
||||
message = "태그 필터링"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
|
||||
# Excel 애플리케이션을 백그라운드에서 실행
|
||||
app = xw.App(visible=False)
|
||||
logger.debug("xlwings 시작")
|
||||
# 로그 설정
|
||||
logger.debug("엑셀 저장 로그기록 파일 생성")
|
||||
|
||||
# 데이터베이스에서 필요한 데이터 로드
|
||||
conn = sqlite3.connect(db_name)
|
||||
query = "SELECT MatchingUrl, keyword, MatchingCat, delvFee, packingFee, plusFee, manuTag, merged_price FROM NaverShopping WHERE MatchingUrl IS NOT NULL"
|
||||
query2 = "SELECT MatchingUrl, keyword, MatchingCat, delvFee, packingFee, plusFee, manuTag, price FROM NaverShopping WHERE MatchingUrl IS NOT NULL"
|
||||
try:
|
||||
df = pd.read_sql_query(query, conn)
|
||||
except:
|
||||
df = pd.read_sql_query(query2, conn)
|
||||
conn.close()
|
||||
logger.debug("DB 읽기 완료")
|
||||
message = "DB 읽기 완료"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
# 'manuTag' 필드에서 '오늘' 단어 제거
|
||||
df['manuTag'] = df['manuTag'].apply(lambda x: ','.join([word for word in str(x).split(',') if '오늘' not in word.strip()]))
|
||||
logger.debug("태그 필터링")
|
||||
message = "태그 필터링"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
|
||||
# Excel 애플리케이션을 백그라운드에서 실행
|
||||
app = xw.App(visible=False)
|
||||
logger.debug("xlwings 시작")
|
||||
except Exception as e:
|
||||
logger.debug(e)
|
||||
# 예외를 로그에 기록
|
||||
logging.error(f"파일 저장 준비 중 예외 발생: {str(e)}", exc_info=True)
|
||||
message = f"파일 저장 준비 중 예외 발생: {str(e)}"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
|
||||
try:
|
||||
# 50개 행씩 나누어 파일 저장
|
||||
|
|
@ -1079,16 +1090,17 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
|
||||
final_delv = 0
|
||||
|
||||
if 'sourcingman' in self.db_name or 'copyman' in self.db_name:
|
||||
final_price = math.ceil((row['price'])*0.98 / 100) * 100 # 2%가격을 낮춘 후 100원단위 올림
|
||||
|
||||
else:
|
||||
# final_delv = row['delvFee'] + row['packingFee']
|
||||
# final_price = row['plusFee']
|
||||
final_price = row['murged_price']
|
||||
|
||||
# 데이터 삽입
|
||||
for index, row in df_subset.iterrows():
|
||||
if 'sourcingman' in self.db_name or 'copyman' in self.db_name:
|
||||
final_price = math.ceil((row['price'])*0.98 / 100) * 100 # 2%가격을 낮춘 후 100원단위 올림
|
||||
else:
|
||||
# final_delv = row['delvFee'] + row['packingFee']
|
||||
if not row['murged_price']:
|
||||
final_price = row['plusFee']
|
||||
final_price = row['murged_price']
|
||||
|
||||
row_num = 4 + (index % 50)
|
||||
ws.range(f'B{row_num}').value = row['MatchingUrl']
|
||||
ws.range(f'C{row_num}').value = row['keyword']
|
||||
|
|
@ -1117,7 +1129,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
except Exception as e:
|
||||
logger.debug(e)
|
||||
# 예외를 로그에 기록
|
||||
logging.error(f"파일 저장 중 예외 발생: {str(e)}")
|
||||
logging.error(f"파일 저장 중 예외 발생: {str(e)}", exc_info=True)
|
||||
message = f"파일 저장 중 예외 발생: {str(e)}"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
finally:
|
||||
|
|
@ -1228,7 +1240,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
except Exception as e:
|
||||
logger.debug(e)
|
||||
# 예외를 로그에 기록
|
||||
logging.error(f"파일 저장 중 예외 발생: {str(e)}")
|
||||
logging.error(f"파일 저장 중 예외 발생: {str(e)}", exc_info=True)
|
||||
message = f"파일 저장 중 예외 발생: {str(e)}"
|
||||
log_dialog.add_log_message(message) # 로그 다이얼로그에 메시지 추가
|
||||
finally:
|
||||
|
|
@ -1371,7 +1383,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.addmargin_spbox.setValue(int(additional_margin)) # 올바른 방법으로 값을 설정
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"가격 오류 : {e}")
|
||||
logger.debug(f"가격 오류 : {e}", exc_info=True)
|
||||
|
||||
try:
|
||||
cat1 = index.sibling(index.row(), 9).data()
|
||||
|
|
@ -1400,7 +1412,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.catbox4.setText(cat4)
|
||||
self.catcodebox.setText(cat_code)
|
||||
except Exception as e:
|
||||
logger.debug(f"카테고리 오류 : {e}")
|
||||
logger.debug(f"카테고리 오류 : {e}", exc_info=True)
|
||||
|
||||
# 카테고리 코드 박스가 비어있을 경우 붉은색으로 경고표시
|
||||
self.check_and_set_color()
|
||||
|
|
@ -1431,7 +1443,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
logger.debug(f"이미지 로드 실패: {localImagePath}")
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"이미지 클립보드 복사 오류: {e}")
|
||||
logger.debug(f"이미지 클립보드 복사 오류: {e}", exc_info=True)
|
||||
|
||||
# 선택된 행의 ID 가져오기 (ID가 첫 번째 열에 있다고 가정)
|
||||
self.selected_row_id = index.sibling(index.row(), 14).data()
|
||||
|
|
@ -1565,10 +1577,10 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
#getattr(self, f'sel_itembox{i+1}2').setText(manuTags[i])
|
||||
|
||||
except sqlite3.OperationalError as e:
|
||||
logger.debug(f"SQL 오류: {e}")
|
||||
logger.debug(f"SQL 오류: {e}", exc_info=True)
|
||||
QtWidgets.QMessageBox.warning(self, "오류", "DB에서 데이터를 가져오는 중 오류가 발생했습니다.")
|
||||
except Exception as e:
|
||||
logger.debug(f"일반 오류: {e}")
|
||||
logger.debug(f"일반 오류: {e}", exc_info=True)
|
||||
QtWidgets.QMessageBox.warning(self, "오류", "알 수 없는 오류가 발생했습니다.")
|
||||
|
||||
self.update_match_count()
|
||||
|
|
@ -1695,7 +1707,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
logger.debug(f"Failed to download image: {url}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.debug(f"Error downloading image {url}: {e}")
|
||||
logger.debug(f"Error downloading image {url}: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def load_images_by_keyword_id(self, keyword_id):
|
||||
|
|
@ -2066,7 +2078,7 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.scraping_thread.finished.connect(self.start_image_save_thread) # 스크래핑 완료 후 이미지 저장 스레드 시작
|
||||
self.scraping_thread.start()
|
||||
except Exception as e:
|
||||
logger.debug(f"에러발생 : {e}")
|
||||
logger.debug(f"에러발생 : {e}", exc_info=True)
|
||||
|
||||
def click_image_save_btn(self):
|
||||
# QMessageBox.information(self, "알림", "네이버 이미지 저장 시작!")
|
||||
|
|
@ -2483,6 +2495,10 @@ def send_exit_message():
|
|||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# 프로그램 종료 시 호출될 함수 등록
|
||||
atexit.register(restore_sleep_mode)
|
||||
atexit.register(record_logout_time)
|
||||
|
||||
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
|
||||
app = QApplication(sys.argv)
|
||||
|
||||
|
|
|
|||
BIN
temp_image.jpg
BIN
temp_image.jpg
Binary file not shown.
|
Before Width: | Height: | Size: 204 KiB After Width: | Height: | Size: 97 KiB |
Loading…
Reference in New Issue