From b04b05e4da19637296d1aee4b5b8a3baa2358c0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=93=AD=E5=9D=A4?= <10372463+ming-kun@user.noreply.gitee.com> Date: Wed, 22 Apr 2026 00:51:41 +0800 Subject: [PATCH] modified: amazon/__pycache__/approve.cpython-39.pyc modified: amazon/__pycache__/main.cpython-39.pyc modified: amazon/__pycache__/match_action.cpython-39.pyc new file: amazon/__pycache__/price_match.cpython-39.pyc modified: amazon/__pycache__/tool.cpython-39.pyc modified: amazon/approve.py new file: amazon/asin_status.py modified: amazon/main.py modified: amazon/price_match.py new file: "amazon/price_match_\346\227\247.py" modified: amazon/tool.py modified: assets/convert.js modified: assets/dedupe.js modified: assets/delete-brand.js modified: assets/split.js modified: new_web_source/convert.html modified: new_web_source/dedupe.html modified: new_web_source/delete-brand.html modified: new_web_source/split.html deleted: web_source/admin.html deleted: "web_source/brand - \345\211\257\346\234\254.html" deleted: "web_source/brand-\346\227\247.html" deleted: web_source/brand.html deleted: web_source/home.html deleted: web_source/index.html deleted: web_source/login.html --- app/amazon/__pycache__/approve.cpython-39.pyc | Bin 32208 -> 32409 bytes app/amazon/__pycache__/main.cpython-39.pyc | Bin 17469 -> 17567 bytes .../__pycache__/match_action.cpython-39.pyc | Bin 18786 -> 18927 bytes .../__pycache__/price_match.cpython-39.pyc | Bin 0 -> 28981 bytes app/amazon/__pycache__/tool.cpython-39.pyc | Bin 3949 -> 5418 bytes app/amazon/approve.py | 11 +- app/amazon/asin_status.py | 0 app/amazon/main.py | 10 +- app/amazon/price_match.py | 1215 +++++++++++++--- app/amazon/price_match_旧.py | 1270 +++++++++++++++++ app/amazon/tool.py | 46 + 11 files changed, 2335 insertions(+), 217 deletions(-) create mode 100644 app/amazon/__pycache__/price_match.cpython-39.pyc create mode 100644 app/amazon/asin_status.py create mode 100644 app/amazon/price_match_旧.py diff --git a/app/amazon/__pycache__/approve.cpython-39.pyc b/app/amazon/__pycache__/approve.cpython-39.pyc index b1fa641ac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{?;O{(+3!u7)5Kld5<)AQ)xD_*>G|`M!I`#vn2-h zWOxkJRf<2I^}O}Hx(af3Kazo%wH7&M9ge0TWZjM?t;Og<{|s&t2!n#Jhw6#~A@D;4 zbVi+7h{@Pb6-Z#*!|a(@Cxf^4)A%!hclNpV7b+aLmCgYQAMGQ_HyTDidtL#I*voxO z6b9^T2Q@D)-WZ%^uwwrhy2&t_N)1yuYcC%CB%|`^Z-Bg2KJg1)+7C`1qR?wCpBnlD DnT!zf diff --git a/app/amazon/__pycache__/price_match.cpython-39.pyc b/app/amazon/__pycache__/price_match.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9ca6b69a7b726c46620ed331a307183eaaef221 GIT binary patch literal 28981 zcmbt-3v?UTc_wD?20;*fh@vD)f~Y5CQ7=E@s+KL;l58aoqhl#?0$D~N4n%+f93N_RPulbQ^(>ZntUo)Vo=? zjraThI~anL5#m@R_`2GWYvG^mu;Ghx$(g9=73IoX|WT z!((W9PfGo2DNUaBlrF#ClvjRzDWClMQ-1jkqyqTW^TB~&DyT87Hy;`Zr@{k~R79S& zd_$@M;l6xypfS}r5KF}*+@Eh6h^OKM&8g;rmQ>3?YpPYk1NpXrd8v5=?Wy*G`KkE> z9jOk42aV7Jp40*(Y(((8@K%q}U_>AA7||1YY7w3qjToL{*~SyzR41OBj5wa-c)K{e z#ArUEk80-M7%fJt(Pqp$>rE{++EWQ*erj1ZW^|m;G*7lOyYz&X>dJPFEzc&#wbTmS zt;{aN-74Iz9`~RY3sP&0g{h>mD7CiFle#Lq&geX$?eHAG=%$KDBB8rb0yh zZuD$q`YqXOvl~ueB#!u4|LkUCiIeiWY%;qxdzG>Dv=`+sxl2!dBy~OBC$b-T+G8xs zUjMY`oR4vl%Xx%%@!rt(dXmehIRkoeGf){U+?*+9?dXwQKA#>k2Ya){V$x?f7Y`5Kn=TBNa))xg878qC`?94p zf``(%!l6NXftei`yeFG34rP0DnS8qUaK_B^ma=Bio>v^o=Su0`vT0@uy~F8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=>cVotgxyq=%(^`cMm4}JZq z-Czjtrl{kub+Q8{5d=;1<6$7d|1SJmH#9m|Kq^xCBv%y1QIg>Z##gZ5k>R7WmHL%i zbZNeJ_l{M5XqA_03lp`okL`QkImQ>&8Jb(Po?fqAx?*1{(WTV<^Ym$2%E6?Tc}%~b zSy}#p=6-#i&NL3Rem_U=WL{Jk{LgLzDfu$bM(o@Hpi@^!Y&F{$SsT$@1U{ zHU-T%65vT6L}j)_qF9Mzm28EX)4am$TM3Shoy6gkmcWrwB^r(#SBMhPG0}8b*F~9CHbTX8>OVAeFhs`N%1PDwpb5UXmm``cgu}#WJq4k z7V0lu1?+n934M~Y%CkUBYGdWnGf!%>rRH*a<;-#uhE_AQTwaIyREZk+JwnFFkPKAV zH?FObY?aSDN!Uv_>FwVfY$rd!hCEi%lUAi-mD9|anw|oR?D>NI=#rhAqq)m;y2Nfu zy4uA42ldw39j&v=X|VcS!=g_o>&41O-D?*gtTN4r1~DAuQyqQ7ht=L)!$XII&ZTCIanrM&H`sMDnjrnK&2(v4A(7*z zOGzYfTs5Tz^QLr+j2Q`2YKRhWkvEyIlu(GSg?w=%b_A1DIHBlp3*)BiB;!;wMYe8A zF-4CY|L-mCX~Ysx$cx;9h(zAayJ0M%PPCaP2Vu>0hr=;tG#(Bc z>}`O8-McTi=fe%fE7O_B^~v)ALBf6{{ofZdB6Yw delta 200 zcmZ3b^;V8Ak(ZZ?0SK(!Ze=nHPUMqeOqr-{qsyJjn#!8OGKVRJHHEE(HHs~T2PBfp zl*OLHF^4&YGldH%%8|kt%%I7;@ku8aBhThM?q^JlwP`pSQB*_t!T3nEy eSDab|GGOv^5oIAhAcKjK2MD>CIT(4Eh1>xy&?~_J diff --git a/app/amazon/approve.py b/app/amazon/approve.py index ce9a933..5d86c4b 100644 --- a/app/amazon/approve.py +++ b/app/amazon/approve.py @@ -1095,7 +1095,16 @@ class ApproveTask: for retry in range(max_retries): try: self.log(f"尝试切换到国家 {country_name} (第 {retry + 1}/{max_retries} 次)") - + if retry > 1: + # 刷新不行就重新打开店铺 + self.log("重试前重新打开店铺...") + try: + driver.close_store() + time.sleep(3) + driver.open_shop(shop_name) + except Exception as e: + self.log(f"关闭重新打开店铺: {str(e)}", "WARNING") + # 如果不是第一次尝试,先刷新页面 if retry > 0: self.log("重试前刷新页面...") diff --git a/app/amazon/asin_status.py b/app/amazon/asin_status.py new file mode 100644 index 0000000..e69de29 diff --git a/app/amazon/main.py b/app/amazon/main.py index 0e072bc..91b664a 100644 --- a/app/amazon/main.py +++ b/app/amazon/main.py @@ -8,6 +8,7 @@ from config import JSON_TASK_QUEUE, runing_task, runing_shop, DELETE_BRAND_API_B from amazon.del_brand import AmazoneDriver, kill_process from amazon.approve import ApproveTask from amazon.match_action import MatchTak +from amazon.price_match import PriceTask from amazon.tool import get_shop_info,show_notification @@ -53,7 +54,8 @@ class TaskMonitor: task_type_info = { "product-risk-resolve-run" : "产品风险审批", - "shop-match-run" : "匹配价格" + "shop-match-run" : "匹配价格", + "price-track-run" : "跟价" } try: while self.running: @@ -119,7 +121,8 @@ class TaskMonitor: try: TASK_INFO = { "产品风险审批" : ApproveTask, - "匹配价格" : MatchTak + "匹配价格" : MatchTak, + "跟价" : PriceTask } self.log(f"线程 {id(task_data)} 开始处理产品风险审批任务...") # 创建ApproveTask实例并处理任务 @@ -129,8 +132,7 @@ class TaskMonitor: self.log(f"线程 {id(task_data)} 产品风险审批任务处理完成") except Exception as e: self.log(f"线程 {id(task_data)} 产品风险审批任务处理异常: {traceback.format_exc()}", "ERROR") - - + def process_task(self, task_data: Dict[str, Any]): """处理单个任务 diff --git a/app/amazon/price_match.py b/app/amazon/price_match.py index a8d9916..08e393f 100644 --- a/app/amazon/price_match.py +++ b/app/amazon/price_match.py @@ -1,71 +1,121 @@ +import json +import sys +import os +import io +# sys.stdout.reconfigure(encoding='utf-8') + import time import re import traceback from datetime import datetime from DrissionPage import Chromium, ChromiumOptions +import requests from amazon.del_brand import AmamzonBase, kill_process -from amazon.tool import show_notification,get_shop_info +from amazon.tool import show_notification,get_shop_info,remove_special_characters,split_currency_values + +from config import runing_task, runing_shop,base_dir,DELETE_BRAND_API_BASE + + +def calculate_target_price( + front_end_data,current_Price,current_shop_name, + recommended_price,recommended_shipping +): + """ + + recommended_price 推荐价格 + recommended_shipping 推荐运费 + """ + # --- Step 1: 获取基础数据 --- + cart_seller = front_end_data.get("cart_seller") + + my_price = current_Price # 我当前的售价 + + is_my_buybox = True if cart_seller == current_shop_name else False # 当前是否自己占据购物车 + + # --- Step 2: 紫鸟后台特殊判定 (最高优先级) --- + if recommended_shipping > 0: + backend_base_price = recommended_price + backend_shipping = recommended_shipping + total_price = backend_base_price + backend_shipping + + if is_my_buybox: + # 🌟【逻辑更新】:如果是自己的购物车,直接跳过,不做任何价格调整 + return None + else: + # 不是自己的购物车:直接将紫鸟的总和作为"第一名"价格,强制抛入阶梯跟价逻辑 + return calculate_standard_competitor_pricing(my_price, total_price) + + # --- Step 3: 常规核心分流逻辑 (如果没有紫鸟后台数据) --- + + # 分支 A:第一名是 Amazon US 卖家 (特殊强敌优先) + price_1 = float(front_end_data.get("top_sellers")[0].get("price")) # 实际第一名价格 + if "Amazon." in cart_seller: + diff = abs(my_price - price_1) + if diff <= 5.0 or my_price > price_1: + return price_1 - 5.0 + elif 5.0 < diff <= 8.0: + return price_1 - 3.0 + elif 8.0 < diff <= 12.0: + return None # 跳过,不跟价 + + + # 分支 B:不是 Amazon US,且目前是自己的购物车 + elif is_my_buybox: + price_2 = float(front_end_data.get("top_sellers")[1].get("price")) # 实际第二名价格 + + diff_with_2nd = price_2 - my_price + if diff_with_2nd >= 2.0: + return price_2 - 0.3 + else: + # 提价区间判定 + if (20 <= my_price <= 30) and diff_with_2nd >= 4: + return price_2 - 0.3 + elif (30 <= my_price <= 60) and diff_with_2nd >= 8: + return price_2 - 0.3 + elif (60 <= my_price <= 150) and diff_with_2nd >= 15: + return price_2 - 0.3 + else: + return None + + + # 分支 C:不是 Amazon US,也不是自己的购物车 + else: + # 正常情况下的普通跟价,调用阶梯逻辑 + return calculate_standard_competitor_pricing(my_price, price_1) + + +# ===================================================================== +# --- 辅助函数:封装“不是自己购物车”的阶梯降价逻辑 --- +# ===================================================================== +def calculate_standard_competitor_pricing(my_current_price, target_competitor_price): + # 基础策略:比目标价格低0.3 + base_target = target_competitor_price - 0.3 + + # 计算当前价格与目标价格的差值 + diff = abs(my_current_price - target_competitor_price) + + # 根据阶梯执行跟价扣减 + if diff <= 0.3: + return base_target - 0.5 + elif 0.5 <= diff <= 0.8: + return base_target - 0.7 + elif 0.8 <= diff <= 1.5: + return base_target - 1.0 + elif 1.5 <= diff <= 2.5: + return base_target - 1.0 + elif diff > 2.5: + return my_current_price # 差距过大,跳过不跟价 + + -from config import runing_task, runing_shop,base_dir class ChromeAmzone: - mark_name = "亚马逊详情采集" - country_info = { - "英国": { - "url": "https://www.amazon.co.uk/dp/B0CJ8SNXXV", - "zip_code": "SW1A 1AA" - }, - "德国": { - "url": "https://www.amazon.de/dp/B0CC8CW9G2?th=1", - "zip_code": "10115" - }, - "法国": { - "url": "https://www.amazon.fr/dp/B0FRG1MJ8H?th=1", - "zip_code": "75001" - }, - "西班牙": { - "url": "https://www.amazon.es/dp/B08ZXVNYNN", - "zip_code": "28001" - }, - "意大利": { - "url": "https://www.amazon.it/dp/B0D1P17T2Q", - "zip_code": "20121" - } - } - - def __init__(self): - """ - 杀死当前谷歌浏览器进程,并使用 drissionpage 启动谷歌浏览器,使用系统安装的浏览器默认用户文件夹 - """ - # 杀死现有的Chrome进程 - print("正在关闭现有的Chrome浏览器进程...") - import os - os.system('taskkill /f /t /im chrome.exe') - time.sleep(2) - - print("正在启动Chrome浏览器...") - # sellersprite_plug_path = os.path.join(base_dir,"app_resource","sellersprite-extension-mv3") - sellersprite_plug_path = os.path.join("D:\\私单交付\\maixiang_AI\\","app_resource","sellersprite-extension-mv3") - print(sellersprite_plug_path) - # 配置浏览器选项 - co = ChromiumOptions() - # co.use_system_user_path(on_off=True) - co.set_user_data_path(r"D:\私单交付\maixiang_AI\user_data\chrome_data") - co.set_local_port(port=19890) - co.add_extension(sellersprite_plug_path) - # co.set_argument('--disable-features=DisableLoadExtensionCommandLineSwitch') - # co.set_argument('--load-extension',sellersprite_plug_path) - co.set_browser_path(r'D:\私单交付\maixiang_AI\app_resource\chrome-win\chrome.exe') - - # 使用系统默认的用户数据目录 - # co.set_user_data_path(r'C:\Users\{}\AppData\Local\Google\Chrome\User Data'.format(os.getenv('USERNAME'))) - self.browser = Chromium(co) - self.tab = self.browser.latest_tab - print("Chrome浏览器启动成功") + def __init__(self,tab): + self.tab = tab def close_init_popup(self): """ @@ -87,7 +137,7 @@ class ChromeAmzone: accept_btn[0].click() - def run(self, country, asin): + def run(self): """ 运行亚马逊详情采集任务 @@ -99,48 +149,18 @@ class ChromeAmzone: dict: 包含采集到的数据 """ try: - # 验证国家是否支持 - if country not in self.country_info: - error_msg = f"不支持的国家: {country},支持的国家有: {list(self.country_info.keys())}" - print(error_msg) - show_notification(error_msg, "error") - return None - - # 获取国家配置 - country_config = self.country_info[country] - zip_code = country_config["zip_code"] - - # 1. 根据国家和ASIN拼接链接 - base_url = country_config["url"] - # 提取域名部分 - domain = base_url.split("/dp/")[0] - # 拼接新的URL - product_url = f"{domain}/dp/{asin}" - print(f"正在访问: {product_url}") - - # 打开链接 - self.tab.get(product_url) - time.sleep(3) # 等待页面初步加载 + self.tab.wait.doc_loaded(timeout=30, raise_err=False) - - # 2. 切换国家/设置邮编 - print(f"正在检查并设置邮编: {zip_code}") - self._set_zip_code(zip_code) self.close_init_popup() - + self.tab.wait.doc_loaded(timeout=5,raise_err=False) + # 3. 抓取数据 print("正在抓取商品数据...") data = self._scrape_data() - - # 添加基本信息 - data['country'] = country - data['asin'] = asin - data['url'] = product_url data['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') - - print(f"数据抓取完成: {data}") + print(f"数据抓取完成: {json.dumps(data)}") return data except Exception as e: @@ -148,84 +168,7 @@ class ChromeAmzone: print(error_msg) show_notification(f"采集失败: {str(e)}", "error") return None - - def _set_zip_code(self, zip_code): - """ - 设置邮编 - - Args: - zip_code: 目标邮编 - """ - try: - # 检查当前邮编 - zip_display = self.tab.ele('xpath://div[@id="glow-ingress-block"]', timeout=10) - - if zip_display: - current_text = zip_display.text - print(f"当前地址信息: {current_text}") - - # 检查是否已经包含目标邮编 - if zip_code in current_text: - print(f"邮编已经设置为: {zip_code},无需修改") - return True - - # 需要设置邮编 - print(f"正在设置邮编为: {zip_code}") - - # 点击地址选择按钮 - location_link = self.tab.ele('xpath://a[@id="nav-global-location-popover-link"]', timeout=10) - if not location_link: - print("找不到地址设置按钮") - return False - - location_link.click() - time.sleep(1) - - # 等待邮编输入框出现 - zip_input = self.tab.ele('xpath://input[@id="GLUXZipUpdateInput"]', timeout=10) - if not zip_input: - print("找不到邮编输入框") - return False - - # 输入邮编 - zip_input.input(zip_code, clear=True) - time.sleep(0.5) - - # 点击提交按钮 - submit_btn = self.tab.ele('xpath://input[@aria-labelledby="GLUXZipUpdate-announce"]', timeout=10) - if not submit_btn: - print("找不到提交按钮") - return False - - submit_btn.click() - - # 等待提交按钮消失(表示请求已发送) - print("等待邮编更新...") - time.sleep(2) - - # 等待页面加载完成 - self.tab.wait.doc_loaded(timeout=30, raise_err=False) - time.sleep(2) - - # 验证邮编是否设置成功 - zip_display_after = self.tab.ele('xpath://div[@id="glow-ingress-block"]', timeout=10) - if zip_display_after: - updated_text = zip_display_after.text - print(f"更新后的地址信息: {updated_text}") - - if zip_code in updated_text: - print(f"邮编设置成功: {zip_code}") - return True - else: - print(f"邮编设置可能失败,当前显示: {updated_text}") - return False - - return True - - except Exception as e: - print(f"设置邮编时出错: {traceback.format_exc()}") - return False - + def _scrape_data(self): """ 抓取商品数据 @@ -241,6 +184,8 @@ class ChromeAmzone: try: # 等待页面加载 time.sleep(3) + h4 = self.tab.eles('xpath://div[@id="rightCol"]//h4[text()="卖家精灵-库存监控"]',timeout=10) + print("【家精灵-库存监控】数量",len(h4)) # 1. 获取前两名卖家的价格和库存(来自 sellersprite 插件) print("正在抓取卖家排名数据...") @@ -256,12 +201,10 @@ class ChromeAmzone: try: # 提取价格和库存信息 # 注意:需要根据实际的HTML结构调整选择器 - text_content = table.text - print(f"第{idx+1}名卖家数据: {text_content}") + # print(f"第{idx+1}名卖家数据: {text_content}") seller_info = { 'rank': idx + 1, - 'raw_data': text_content } # 尝试提取更结构化的数据 @@ -270,14 +213,15 @@ class ChromeAmzone: try: # 示例:查找价格和库存的具体子节点 price_ele = table.ele('xpath:.//span[contains(@class,"price")]', timeout=2) - stock_ele = table.ele('xpath:.//span[contains(@class,"stock")]', timeout=2) + stock_ele = table.ele('xpath:.//span[@class="surplus-count-num"]', timeout=2) + shop_name_ele = table.ele('xpath:.//div[@class="surplus-table-item"][2]//a', timeout=2) - if price_ele: - seller_info['price'] = price_ele.text.strip() - if stock_ele: - seller_info['stock'] = stock_ele.text.strip() - except: - # 如果找不到具体元素,就使用原始文本 + seller_info['price'] = remove_special_characters(price_ele.text.strip()) + seller_info['stock'] = remove_special_characters(stock_ele.text.strip()) + seller_info['shop_name'] = shop_name_ele.text.strip() + + except Exception as e: + print("解析出错",e) pass data['top_sellers'].append(seller_info) @@ -286,6 +230,7 @@ class ChromeAmzone: print(f"解析第{idx+1}名卖家数据失败: {str(e)}") else: print("未找到 sellersprite 插件数据,可能插件未启用") + show_notification("未找到 sellersprite 插件数据,可能插件未启用") # 2. 获取购物车所属卖家 print("正在抓取购物车卖家信息...") @@ -318,47 +263,893 @@ class ChromeAmzone: def close(self): """关闭浏览器""" try: - if self.browser: - self.browser.quit() - print("浏览器已关闭") + self.tab.close() except Exception as e: - print(f"关闭浏览器时出错: {str(e)}") + print(f"关闭标签页时出错: {str(e)}") class AmzonePriceMatch(AmamzonBase): mark_name = "跟价" - pass + def SwitchPage(self): + """ + 切换至 管理所有库存页面 + 1、等待 //navigation-favorites-bar[@class="hydrated"] 出现 + """ + navigation = self.tab.ele('xpath://navigation-favorites-bar[@class="hydrated"]') + navigation.wait.displayed(raise_err=False) + page_btn = navigation.sr('xpath://internal-fav-bar-links[@data-internal="navigation"]').sr( + 'xpath://a[@data-page-id="ezdpc-gui-inventory-mons"]') + page_btn.wait.displayed(raise_err=False) + page_btn.click(timeout=5) + + self.tab.wait.doc_loaded() + # 等待搜索框出现 + search_region = self.tab.ele('xpath://div[@id="searchBoxContainer"]//kat-input-group') + search_region.wait.displayed(raise_err=False,timeout=60) + + def search(self,filter_type="ApprovalRequired"): + sku_ls = [] + + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]",timeout=5) + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + drop_down = self.tab.ele('xpath://div[contains(@class,"VolusListingStatusDropDown-module__verticalContainer")]//kat-dropdown') + drop_down.wait.displayed(raise_err=False) + drop_down.wait.enabled(raise_err=False) + time.sleep(0.6) + drop_down.click() + # //kat-option[@value="SearchSuppressed"] + xp = f'xpath://kat-option[@value="{filter_type}"]' + print(f"【{self.mark_name}】正在寻找筛选条件 {filter_type},xpath: {xp}") + approval_required = self.tab.eles(xp,timeout=5) + if len(approval_required) == 0: + print(f"【{self.mark_name}】没有需要{filter_type}选项】没有需要{filter_type}的商品了") + return sku_ls # "没有需要审批的商品了" + else: + approval_required = approval_required[0] + approval_required.wait.displayed(raise_err=False) + approval_required.click() + + approval_required_text = approval_required.text + print(f"【{self.mark_name}】已选择筛选条件: {approval_required_text}") + + count = re.findall(r'\d+', approval_required_text) + if count: + count = int(count[0]) + print(f"【{self.mark_name}】待审批的商品数量: {count}") + if count <= 0: + print(f"【{self.mark_name}】没有需要{filter_type}的商品了") + return sku_ls #"没有需要审批的商品了" + for _ in range(3): + # 等待加载完成 + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]") + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + sku_ls = self.tab.eles("xpath://div[@data-sku]",timeout=3) + if len(sku_ls) > 0: + break + approval_required.click() + return sku_ls + + def search_asin(self, asin): + search_region = self.tab.ele('xpath://div[@id="searchBoxContainer"]//kat-input-group') + search_region.wait.displayed(raise_err=False) + time.sleep(0.6) + search_input = self.tab.ele("xpath://kat-input[contains(@class,'SearchBox-module__searchInput')]").sr( + 'xpath://span[@class="container"]//input[@part="input"]') + search_input.input(asin,clear=True) + sku_ls = [] + for _ in range(3): + search_btn = self.tab.ele("xpath://kat-icon[@name='search']") + search_btn.click() + + load_ele = self.tab.ele("xpath://div[contains(@class,'Loader-module__loader')]") + # load_ele.wait.hidden(timeout=3, raise_err=False) + load_ele.wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + sku_ls = self.tab.eles("xpath://div[@data-sku]",timeout=3) + if len(sku_ls) > 0: + break + return sku_ls + + def search_asin_action(self,asin:str): + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]", timeout=5) + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + sku_ls = self.search_asin(asin=asin) + print(f"【{self.mark_name}】{asin} 搜索到 {len(sku_ls)} 个SKU") + + def clear_tab(self): + all_tab = self.browser.get_tabs() + close_tab = [] + for tab in all_tab: + tab_id = tab if isinstance(tab,str) else tab.tab_id + if self.tab.tab_id == tab_id: + continue + close_tab.append(tab) + print("需要关闭的标签页",close_tab) + print("当前操作的tab_id",self.tab.tab_id) + self.browser.close_tabs(close_tab) + + def run_page_action(self,current_shop_name:str,appoint_asin:str=None,skip_asin:list=[]): + print(f"【{self.mark_name}】,开始执行") + num = 0 + retry_num = 0 + already_asin = set() + get_page_faild = 0 + #获取当前国家 + current_country_ele = self.tab.ele('xpath://div[@class="dropdown-account-switcher-header-label"]/span[last()]', + timeout=20) + current_country = current_country_ele.text.strip() + + while retry_num < 3: # 最多重试3次 + try: + if appoint_asin is not None: + print(self.mark_name,"指定asin操作",appoint_asin) + self.search_asin_action(asin=appoint_asin) + + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]", timeout=5) + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + # 获取当前页码 + try: + page_pamel = self.tab.eles('xpath://kat-pagination', timeout=5) + if len(page_pamel) > 0: + current_page = page_pamel[0].sr('xpath:.//ul[@class="pages"]//li[@aria-current="true"]').text + + # 总页数 + total_page = page_pamel[0].sr.eles( + 'xpath:.//ul[@class="pages"]//span[@class="page__inner"][last()]') + if len(total_page) > 0: + total_page = total_page[-1].text + else: + total_page = 0 + print(f"【{self.mark_name}】当前页码: {current_page} / 总页数: {total_page}") + get_page_faild = 0 + except Exception as e: + print("【{self.mark_name}】","获取页码失败", e) + get_page_faild += 1 + if get_page_faild > 2: + show_notification(f"【{self.mark_name}】获取页码失败超3次停止任务!") + break + + sku_ls = self.tab.eles("xpath://div[@data-sku]", timeout=10) + print(f"【{self.mark_name}】获取到 {len(sku_ls)}") + # for sku_ele in sku_ls[0:2]: + for sku_ele in sku_ls: + + asin = sku_ele.ele( + 'xpath:.//div[contains(@class,"JanusSplitBox-module__container")]//div[contains(@class,"JanusSplitBox-module__panel--") and contains(string(.),"ASIN")]/..//div[last()]', + timeout=3).text + print(f"【{self.mark_name}】ASIN {asin} 找到....") + if asin in already_asin: + print(f"【{self.mark_name}】{asin} 已经处理过了,跳过") + continue + if asin in skip_asin: + yield (asin, { + "statu": "跳过,需要跳过的ASIN" + }) + continue + bottom_price_ele = sku_ele.eles('xpath:.//div[@data-test-id="LowestPrice"]/div[2]',timeout=5) + bottom_price = "" #初始化为空 + if len(bottom_price_ele) > 0: + try: + bottom_price_text = bottom_price_ele[0].text + # print("最低价格->>",bottom_price_text) + bottom_price = f"{sum(split_currency_values(bottom_price_text))}" + except Exception as e: + print("最低价提取失败",e) + current_price_ele = sku_ele.eles('xpath:.//b[text()="价格"]/../..//kat-input',timeout=5) + if len(current_price_ele) > 0: + current_price = current_price_ele[0].attr("value") + print("获取到当前价格为 ->",current_price) + else: + print(f"{self.mark_name} 没有获取到当前价格") + yield (asin, { + "statu": "失败(没有获取到当前的价格)" + }) + continue + + self.clear_tab() + detail_url_ele = sku_ele.ele('xpath:.//div[contains(@class,"ProductDetails-module__titleContainer")]//a') + # detail_url_ele.click() + detail_url = detail_url_ele.attr("href") + print("详情链接",detail_url) + # time.sleep(1) + for _ in range(10): + try: + new_tab = self.browser.new_tab(url=detail_url) + print("获取新标签页成功",new_tab) + time.sleep(1) + break + except Exception as e: + time.sleep(1) + pass + chrome = ChromeAmzone(tab=new_tab) + front_end_data = chrome.run() + chrome.close() + print(self.mark_name,"亚马逊前台抓取到数据",front_end_data) + # + cart_seller = front_end_data.get("cart_seller") + if cart_seller == current_shop_name and len(front_end_data.get("top_sellers"))< 2: + yield (asin, { + "statu": "跳过(自己的购物车,只有第一名)", + "currentPrice": current_price, + }) + continue + + recommend_price_ele= sku_ele.eles('xpath:.//div[@data-test-id="FeaturedOfferPrice"]/div[2]',timeout=5) + if len(recommend_price_ele) > 0: + try: + price_text = recommend_price_ele[0].text + # print("推荐价格 ->>",price_text) + recommend_price,shipping_fee = split_currency_values(price_text) + except Exception as e: + print("推荐价格和运费提取失败 ->>",e) + recommend_price, shipping_fee = 0, 0 + else: + print(f"{self.mark_name} 没有查找有推荐价格和运费") + recommend_price,shipping_fee = 0,0 + + adjust_prices = calculate_target_price( + front_end_data, float(current_price), current_shop_name, + recommend_price, shipping_fee + ) + # adjust_prices = 236.56 + + print(asin,"-->>",f"【逻辑计算后的价格】",adjust_prices) + if adjust_prices is not None and adjust_prices != float(current_price): + #修改价格 + self.tab.actions.click(current_price_ele[0]) + time.sleep(1) + current_price_ele[0].input(f"{adjust_prices}", clear=True) + time.sleep(1) + # current_price_ele[0].sr('xpath:.//inpu[@part="input"]').input(f"{adjust_prices}",clear=True) + out_focus = sku_ele.ele('xpath:.//b[text()="价格"]/../..//kat-label',timeout=5) + out_focus.click() + time.sleep(1) + save_all_btn = self.tab.ele('xpath://kat-button[@label="保存所有"]', timeout=10) + save_all_btn.wait.displayed(timeout=10, raise_err=False) + save_all_btn.click() + save_all_btn.wait.deleted(timeout=10, raise_err=False) + recommendedPrice = recommend_price + shipping_fee + price_1 = float(front_end_data.get("top_sellers")[0].get("price")) if len(front_end_data.get("top_sellers")) >= 2 else "" # 实际第一名价格 + price_2 = float(front_end_data.get("top_sellers")[1].get("price")) if len(front_end_data.get("top_sellers")) >= 2 else "" # 实际第二名价格 + cartShopName = front_end_data.get("cart_seller") + yield (asin,{ + "statu" : "改价成功", + "currentPrice" : current_price, + "recommendedPrice" : f"{recommendedPrice}", + "minimumPrice" : bottom_price, #最低价格 + "firstPlace": price_1, + "secondPlace": price_2, + "cartShopName" : cartShopName, + "priceChangeStatus" : "改价成功", + }) + already_asin.add(asin) + + # 判断是否存在需要翻页的情况 + page_pamel = self.tab.eles('xpath://kat-pagination', timeout=5) + if len(page_pamel) == 0: + break + next_page_btn = page_pamel[0].sr('xpath:.//span[@part="pagination-nav-right"]') + class_str = next_page_btn.attr('class') + if "end" in class_str: + break + next_page_btn.click() + num += 1 + print(f"【{self.mark_name}】【程序计算】正在翻页,已翻 {num} 页...") + already_asin = set() + + except Exception as e: + print(f"【{self.mark_name}】处理跟价操作异常", e) + traceback.print_exc() + retry_num += 1 + self.tab.refresh() + self.tab.wait.doc_loaded(raise_err=False, timeout=120) + +class PriceTask: + country_info = { + "DE": "德国", + "FR": "法国", + "ES": "西班牙", + "IT": "意大利", + "UK": "英国" + } + + def __init__(self, user_info: dict = None): + """初始化审批任务处理器 + + Args: + user_info: 用户信息字典,包含 company, username, password + """ + self.user_info = user_info or {} + self.running = True + + def log(self, message: str, level: str = "INFO"): + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + if level == "ERROR": + show_notification(message, "error") + print(f"[{timestamp}] [PriceTask] [{level}] {message}") + + def process_task(self, task_data: dict): + """处理审批任务主入口 + + Args: + task_data: 任务数据 + """ + try: + data = task_data.get("data", {}) + task_id = data.get("task_id") + # items = data.get("items", []) + shop_name = data.get("shop_name") + country_codes = data.get("country_codes", []) + risk_listing_filter = data.get("risk_listing_filter", "Active") + user_id = data.get("user_id") + stage_index = data.get("stage_index") + final_stage = bool(data.get("final_stage", True)) + + # 用于测试 + limit = data.get("limit", None) + + if not task_id: + self.log("任务ID为空,跳过", "WARNING") + return + + # if not items: + # self.log("店铺列表为空,跳过", "WARNING") + # return + + if not country_codes: + self.log("国家列表为空,跳过", "WARNING") + return + + self.log(f"开始处理审批任务 {task_id},共 1 个店铺,{len(country_codes)} 个国家") + + from config import runing_task + runing_task[task_id] = { + "status": "running", + "start_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "total_shops": 1, + "processed_shops": 0, + "total_countries": len(country_codes) , + "processed_countries": 0, + "total_asins": 0, + "processed_asins": 0, + "success_count": 0, + "failed_count": 0, + "stop_requested": False + } + + # 检查是否收到暂停请求 + if task_id in runing_task and runing_task[task_id].get("stop_requested", False): + self.log(f"检测到任务 {task_id} 的暂停请求,停止处理", "WARNING") + runing_task[task_id]["status"] = "stopped" + return + + self.log(f"开始处理店铺: {shop_name}") + show_notification(f"开始处理店铺: {shop_name}", "info") + + try: + self.process_shop(data, country_codes, task_id, risk_listing_filter, user_id, stage_index, + final_stage, limit=limit) + + # self.process_shop(shop_item, country_codes, task_id,risk_listing_filter) + # 更新已处理店铺数 + if task_id in runing_task: + runing_task[task_id]["processed_shops"] += 1 + except Exception as e: + import traceback + self.log(f"处理店铺 {shop_name} 失败: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + # 更新任务状态 + if task_id in runing_task: + if runing_task[task_id].get("stop_requested", False): + runing_task[task_id]["status"] = "stopped" + self.log(f"任务 {task_id} 已被暂停!") + else: + runing_task[task_id]["status"] = "completed" + self.log(f"任务 {task_id} 处理完成!") + + except Exception as e: + import traceback + self.log(f"任务处理失败: {traceback.format_exc()}", "ERROR") + if task_id: + from config import runing_task + if task_id in runing_task: + runing_task[task_id]["status"] = "failed" + runing_task[task_id]["error"] = str(e) + + def open_shop(self,max_retries,company_name,shop_name,iskill=False): + error_info = "" + driver = None + for retry in range(max_retries): + try: + self.log(f"尝试打开店铺 {shop_name} (第 {retry + 1}/{max_retries} 次)") + + if iskill: + self.log("重试前先杀掉浏览器进程...") + kill_process("v6") + kill_process("v5") + time.sleep(2) + + # 组装用户信息并创建驱动 + user_info = { + **self.user_info, + "company": company_name + } + driver = AmzonePriceMatch(user_info) + browser = driver.open_shop(shop_name) + + if browser and browser != "店铺不存在": + self.log(f"成功打开店铺 {shop_name}") + else: + self.log(f"打开店铺失败: {browser}", "WARNING") + driver = None + continue + + # 判断是否需要登录 + need_login = driver.need_login() + print("【是否需要登录】:", need_login) + if need_login: + self.log(f"店铺 {shop_name} 需要登录,正在登录...") + # 获取店铺凭证 + response = get_shop_info(shop_name) + print("【获取店铺凭证返回】:", response.text) + shop_data = response.json() + if not shop_data: + mes = f"获取店铺凭证失败,响应数据: {shop_data.get('message', '未知错误')}" + self.log(mes, "ERROR") + show_notification(mes, "ERROR") + continue + + password = shop_data["data"]["password"] + + login_success = driver.login(password) + if login_success: + self.log(f"店铺 {shop_name} 登录成功,正在重新打开店铺...") + browser = driver.open_shop(shop_name) + if browser and browser != "店铺不存在": + self.log(f"成功打开店铺 {shop_name} 登录后") + break + else: + self.log(f"登录后打开店铺失败: {browser}", "WARNING") + driver = None + else: + self.log(f"店铺 {shop_name} 登录失败", "WARNING") + driver = None + else: + break + + except Exception as e: + import traceback + self.log(f"打开店铺异常: {traceback.format_exc()}", "INFO") + driver = None + error_info = str(e) + time.sleep(10) + + # 如果还有重试机会,等待后继续 + if retry < max_retries - 1: + time.sleep(3) + + # 检查是否成功打开 + if not driver or not browser or browser == "店铺不存在": + error_msg = f"店铺 {shop_name} 打开失败,已重试 {max_retries} 次,跳过该店铺,{error_info}" + self.log(error_msg, "ERROR") + # 从执行列表中移除 + if shop_name in runing_shop: + del runing_shop[shop_name] + return driver + return driver + + + def process_shop(self, shop_item: dict, country_codes: list, task_id: int, risk_listing_filter: str, + user_id=None, stage_index=None, final_stage: bool = True, limit: str = None): + """处理单个店铺 + + Args: + shop_item: 店铺信息 + country_codes: 国家代码列表 + task_id: 任务ID + risk_listing_filter: 风险商品筛选条件 + """ + shop_name = shop_item.get("shopName", "未知店铺") + company_name = shop_item.get("companyName", "") + shopMallName = shop_item.get("shopMallName","") + skip_asins_by_country = shop_item.get("skip_asins_by_country",{}) + asin_rows_by_country = shop_item.get("asin_rows_by_country",{}) + + if not company_name: + self.log(f"店铺 {shop_name} 的公司名称为空,跳过", "WARNING") + return + + if task_id in runing_task: + runing_task[task_id]["current_shop"] = shop_name + + # 将店铺添加到正在执行中的店铺列表 + start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + runing_shop[shop_name] = start_time + self.log(f"店铺 {shop_name} 已添加到执行列表,账号: {company_name},开始时间: {start_time}") + + # 店铺打开重试最多3次 + driver = None + max_retries = 3 + + # 打开店铺 + driver = self.open_shop(max_retries=max_retries,company_name=company_name,shop_name=shop_name) + if driver is None: + self.log(f"任务 {task_id} 启动店铺失败,结束任务", "ERROR") + for country_code in country_codes: + self.post_result(task_id, shop_name, country_code, "", {}, shopMallName, is_done=True) + return + try: + # 处理每个国家 + for country_code in country_codes: + # 检查是否收到暂停请求 + if task_id in runing_task and runing_task[task_id].get("stop_requested", False): + self.log(f"检测到任务 {task_id} 的暂停请求,停止处理国家", "WARNING") + break + skip_asin = skip_asins_by_country.get(country_code,[]) #需要跳过的asin + appoint_asin = asin_rows_by_country.get(country_code,[]) + try: + self.process_country(driver, country_code, task_id, shop_name, risk_listing_filter, + shopMallName=shopMallName,skip_asin=skip_asin, limit=limit,appoint_asin=appoint_asin) + except Exception as e: + import traceback + self.log(f"处理国家 {country_code} 失败: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + # 最后回传,标记完成 + try: + # self.post_result(task_id, shop_name, country_code, "", "", is_done=True) + if final_stage: + self.post_result(task_id, shop_name, country_code, "", {},shopMallName,is_done=True) + else: + self.post_stage_finished(task_id, user_id, stage_index) + except Exception as e: + self.log(f"回传结果失败: {str(e)}", "ERROR") + finally: + # 关闭店铺 + try: + if driver: + self.log(f"关闭店铺 {shop_name}") + driver.close_store() + time.sleep(2) + except Exception as e: + self.log(f"关闭店铺失败: {str(e)}", "WARNING") + + # 从正在执行中的店铺列表中移除 + if shop_name in runing_shop: + del runing_shop[shop_name] + self.log(f"店铺 {shop_name} 已从执行列表中移除") + + def process_country(self, driver: AmzonePriceMatch, country_code: str, task_id: int, shop_name: str, + risk_listing_filter: str,shopMallName:str,skip_asin:list,appoint_asin:list,limit: str = None): + """处理单个国家的审批任务 + + Args: + driver: AmzoneApprove驱动实例 + country_code: 国家代码(如 UK, DE, FR 等) + task_id: 任务ID + shop_name: 店铺名称 + risk_listing_filter: 风险商品筛选条件 + """ + + # 转换国家代码为中文名称 + country_name = self.country_info.get(country_code, country_code) + info_mes = f"开始处理国家: {country_name} ({country_code}),需要跳过的asin {skip_asin}" + self.log(info_mes) + show_notification(info_mes, "info") + + # 更新当前处理的国家 + if task_id in runing_task: + runing_task[task_id]["current_country"] = country_name + + # 切换国家,最多重试3次 + max_retries = 3 + switch_success = False + + for retry in range(max_retries): + try: + self.log(f"尝试切换到国家 {country_name} (第 {retry + 1}/{max_retries} 次)") + if retry > 1: + # 刷新不行就重新打开店铺 + self.log("重试前刷新页面...") + try: + driver.close_store() + time.sleep(3) + driver.open_shop(shop_name) + except Exception as e: + self.log(f"关闭重新打开店铺: {str(e)}", "WARNING") + # 如果不是第一次尝试,先刷新页面 + if retry > 0: + self.log("重试前刷新页面...") + try: + driver.tab.refresh() + time.sleep(3) + except Exception as e: + self.log(f"刷新页面失败: {str(e)}", "WARNING") + + switch_success = driver.SwitchingCountries(country_name) + if switch_success: + self.log(f"成功切换到国家 {country_name}") + break + else: + self.log(f"切换到国家 {country_name} 失败", "WARNING") + + except Exception as e: + import traceback + self.log(f"切换国家 {country_name} 异常: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + # 如果还有重试机会,等待后继续 + if retry < max_retries - 1: + time.sleep(2) + + # 如果切换失败,直接返回 + if not switch_success: + error_message = f"切换到国家 {country_name} 失败,已重试 {max_retries} 次,跳过该国家" + self.log(error_message, "ERROR") + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + return + + # 切换到库存管理页面 + for retry in range(max_retries): + try: + driver.SwitchPage() + self.log(f"已切换到库存管理页面") + except Exception as e: + import traceback + self.log(f"切换页面失败: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + if retry >= max_retries-1: + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + self.log(f"切换页面失败重试退出", "ERROR") + return + + # 搜索需要审批的商品,最多重试3次 + sku_ls = [] + for retry in range(max_retries): + try: + self.log(f"尝试搜索匹配操作商品 (第 {retry + 1}/{max_retries} 次)") + sku_ls = driver.search(filter_type=risk_listing_filter) + break + except Exception as e: + self.log(f"搜索商品异常: {str(e)}", "ERROR") + if retry < max_retries - 1: + try: + driver.tab.refresh() + time.sleep(3) + except Exception as refresh_error: + self.log(f"刷新页面失败: {str(refresh_error)}", "WARNING") + + # 如果没有需要审批的商品,直接返回 + if len(sku_ls) == 0: + self.log(f"国家 {country_name} 没有搜索出的商品") + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + return + + self.log(f"国家 {country_name} 搜索出 {len(sku_ls)} 商品,开始处理...") + + # 处理所有需要审批的商品(通过yield获取结果) + try: + # 指定 asin + max_range = max(1,len(appoint_asin)) + for i in range(max_range): + if len(appoint_asin) > i: + _shopMallName = appoint_asin[i]["shopMallName"] + ap_asin = appoint_asin[i]["shopMallName"] + else: + _shopMallName = shopMallName + ap_asin = None + + for asin, status in driver.run_page_action( + current_shop_name=_shopMallName, + appoint_asin=ap_asin,skip_asin=skip_asin + ): + # 检查是否收到暂停请求 + if task_id in runing_task and runing_task[task_id].get("stop_requested", False): + self.log(f"检测到任务 {task_id} 的暂停请求,停止处理ASIN", "WARNING") + break + + self.log(f"ASIN {asin} 处理结果: {status}") + + # 更新任务状态 + if task_id in runing_task: + runing_task[task_id]["current_asin"] = asin + runing_task[task_id]["processed_asins"] += 1 + + runing_task[task_id]["failed_count"] += 1 + + # 回传结果到API + try: + self.post_result(task_id, shop_name, country_code, asin, status,shopMallName) + except Exception as e: + self.log(f"回传结果失败: {str(e)}", "ERROR") + + except Exception as e: + import traceback + self.log(f"处理审批商品异常: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + # 更新已处理国家数 + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + + + self.log(f"国家 {country_name} 处理完成") + + def post_stage_finished(self, task_id: int, user_id, stage_index): + import requests + from config import DELETE_BRAND_API_BASE + + if user_id in (None, "", 0): + raise ValueError("user_id is required for stage completion callback") + if stage_index is None: + raise ValueError("stage_index is required for stage completion callback") + + url = f"{DELETE_BRAND_API_BASE}/api/shop-match/tasks/{task_id}/stage-finished" + payload = {"stage_index": stage_index} + params = {"user_id": user_id} + + max_retries = 3 + for retry in range(max_retries): + try: + self.log(f"Attempting stage completion callback ({retry + 1}/{max_retries})") + response = requests.post( + url, + params=params, + json=payload, + headers={"Content-Type": "application/json"}, + timeout=30, + verify=False, + ) + self.log(f"Stage completion callback response: {response.text}") + data = response.json() if response.text else {} + if response.status_code == 200 and isinstance(data, dict) and data.get("success"): + self.log(f"Stage completion callback succeeded: task={task_id}, stage={stage_index}") + return + self.log(f"Stage completion callback failed, status={response.status_code}", "WARNING") + except Exception as e: + self.log(f"Stage completion callback exception: {str(e)}", "ERROR") + if retry < max_retries - 1: + time.sleep(2) + + raise RuntimeError(f"Stage completion callback failed after retries: task={task_id}, stage={stage_index}") + + def post_result(self, task_id: int, shop_name: str, country_code: str, asin: str, status: dict,shopMallName:str, + is_done: bool = False): + """回传处理结果到API + + Args: + task_id: 任务ID + shop_name: 店铺名称 + country_code: 国家代码 + asin: ASIN + status: 处理状态 + """ + + url = f"{DELETE_BRAND_API_BASE}/api/price-track/tasks/{task_id}/result" + """ + (asin,{ + "statu" : "改价成功", + "currentPrice" : current_price, + "recommendedPrice" : f"{recommendedPrice}", + "minimumPrice" : bottom_price, #最低价格 + "firstPlace": price_1, + "secondPlace": price_2, + "cartShopName" : current_shop_name, + "priceChangeStatus" : "改价成功", + }) + """ + + payload = { + "shops": [ + { + "shopName": shop_name, + "countries": { + "additionalProperties1": [ + { + "shopMallName": shopMallName, + "asin": asin, + "price": status.get("currentPrice") if status.get("currentPrice") else "", + "recommendedPrice": status.get("recommendedPrice") if status.get("recommendedPrice") else "", + "minimumPrice": status.get("minimumPrice") if status.get("minimumPrice") else "", + "firstPlace": status.get("firstPlace") if status.get("firstPlace") else "", + "secondPlace": status.get("secondPlace") if status.get("secondPlace") else "", + "cartShopName": status.get("cartShopName") if status.get("cartShopName") else "", + "priceChangeStatus": "UPDATED", + # "modifyCount": "2", + "status": status.get("statu") + } + ] + }, + "error": "" + } + ] + } + if is_done: + payload["shops"][0]["success"] = is_done + + max_retries = 3 + for retry in range(max_retries): + try: + print("================【跟价】=====================") + self.log(f"尝试回传结果 (第 {retry + 1}/{max_retries} 次)") + self.log(f"回传URL: {url}") + self.log(f"回传数据: {payload}") + response = requests.post( + url, + json=payload, + headers={"Content-Type": "application/json"}, + timeout=30, + verify=False + ) + self.log(f"回传结果: {response.text}") + data = response.json() if response.text else {} + if response.status_code == 200 and isinstance(data, dict) and data.get("success"): + self.log(f"结果回传成功: {asin} - {status}") + return + else: + self.log(f"结果回传失败,状态码: {response.status_code}", "WARNING") + print("=====================================") + + except Exception as e: + self.log(f"调用API异常: {str(e)}", "ERROR") + print("=====================================") + + # 如果还有重试机会,等待后继续 + if retry < max_retries - 1: + time.sleep(2) + + self.log(f"已达到最大重试次数,结果回传最终失败", "ERROR") + raise RuntimeError("已达到最大重试次数,结果回传最终失败") if __name__ == '__main__': # 使用示例 - print("=" * 50) - print("亚马逊详情采集示例") - print("=" * 50) - - try: - # 创建ChromeAmzone实例 - chrome = ChromeAmzone() - - # 示例1:采集英国站点的商品信息 - print("\n示例1:采集英国站点商品") - result1 = chrome.run(country="英国", asin="B0CJ8SNXXV") - if result1: - print(f"采集成功: {result1}") - - # 示例2:采集德国站点的商品信息 - # print("\n示例2:采集德国站点商品") - # result2 = chrome.run(country="德国", asin="B0CC8CW9G2") - # if result2: - # print(f"采集成功: {result2}") - - # # 关闭浏览器 - # print("\n正在关闭浏览器...") - # chrome.close() - - except Exception as e: - print(f"运行出错: {traceback.format_exc()}") - - - + user_info = { + "company": "rongchuang123", + "username": "自动化_Robot", + "password": "#20zsg25" + } + shop_name = "魏振峰" + country = "德国" + kill_process('v6') + driver = AmzonePriceMatch(user_info) + browser = driver.open_shop(shop_name) + sw_suc = driver.SwitchingCountries(country) + driver.SwitchPage() + risk_listing_filter = "Active" + _shopMallName = "WEIZHENFENG168" + ap_asin ="B0F1N18XFW" + skip_asin = [] + for _ in range(3): + try: + sku_ls = driver.search(filter_type=risk_listing_filter) + break + except Exception as e: + print(e) + driver.tab.refresh() + if len(sku_ls) > 0: + print("有数据,开始操作") + for asin, status in driver.run_page_action( + current_shop_name=_shopMallName, + appoint_asin=ap_asin,skip_asin=skip_asin + ): + print(f"ASIN {asin} 的处理结果: {status}") + print("已完成操作") diff --git a/app/amazon/price_match_旧.py b/app/amazon/price_match_旧.py new file mode 100644 index 0000000..59f2864 --- /dev/null +++ b/app/amazon/price_match_旧.py @@ -0,0 +1,1270 @@ +import json +import sys +import os +import io +# sys.stdout.reconfigure(encoding='utf-8') + +import time +import re +import traceback +from datetime import datetime +from DrissionPage import Chromium, ChromiumOptions +import requests + +from amazon.del_brand import AmamzonBase, kill_process +from amazon.tool import show_notification,get_shop_info,remove_special_characters,split_currency_values + +from config import runing_task, runing_shop,base_dir,DELETE_BRAND_API_BASE + + +def calculate_target_price( + front_end_data,current_Price,current_shop_name, + recommended_price,recommended_shipping +): + """ + + recommended_price 推荐价格 + recommended_shipping 推荐运费 + """ + # --- Step 1: 获取基础数据 --- + price_1 = float(front_end_data.get("top_sellers")[0].get("price")) # 实际第一名价格 + cart_seller = front_end_data.get("cart_seller") + + my_price = current_Price # 我当前的售价 + + is_my_buybox = True if cart_seller == current_shop_name else False # 当前是否自己占据购物车 + + # --- Step 2: 紫鸟后台特殊判定 (最高优先级) --- + if recommended_shipping > 0: + backend_base_price = recommended_price + backend_shipping = recommended_shipping + total_price = backend_base_price + backend_shipping + + if is_my_buybox: + # 🌟【逻辑更新】:如果是自己的购物车,直接跳过,不做任何价格调整 + return None + else: + # 不是自己的购物车:直接将紫鸟的总和作为"第一名"价格,强制抛入阶梯跟价逻辑 + return calculate_standard_competitor_pricing(my_price, total_price) + + # --- Step 3: 常规核心分流逻辑 (如果没有紫鸟后台数据) --- + + # 分支 A:第一名是 Amazon US 卖家 (特殊强敌优先) + if "Amazon." in cart_seller: + diff = abs(my_price - price_1) + if diff <= 5.0 or my_price > price_1: + return price_1 - 5.0 + elif 5.0 < diff <= 8.0: + return price_1 - 3.0 + elif 8.0 < diff <= 12.0: + return None # 跳过,不跟价 + + + # 分支 B:不是 Amazon US,且目前是自己的购物车 + elif is_my_buybox: + price_2 = float(front_end_data.get("top_sellers")[1].get("price")) # 实际第二名价格 + + diff_with_2nd = price_2 - my_price + if diff_with_2nd >= 2.0: + return price_2 - 0.3 + else: + # 提价区间判定 + if (20 <= my_price <= 30) and diff_with_2nd >= 4: + return price_2 - 0.3 + elif (30 <= my_price <= 60) and diff_with_2nd >= 8: + return price_2 - 0.3 + elif (60 <= my_price <= 150) and diff_with_2nd >= 15: + return price_2 - 0.3 + else: + return None + + + # 分支 C:不是 Amazon US,也不是自己的购物车 + else: + # 正常情况下的普通跟价,调用阶梯逻辑 + return calculate_standard_competitor_pricing(my_price, price_1) + + +# ===================================================================== +# --- 辅助函数:封装“不是自己购物车”的阶梯降价逻辑 --- +# ===================================================================== +def calculate_standard_competitor_pricing(my_current_price, target_competitor_price): + # 基础策略:比目标价格低0.3 + base_target = target_competitor_price - 0.3 + + # 计算当前价格与目标价格的差值 + diff = abs(my_current_price - target_competitor_price) + + # 根据阶梯执行跟价扣减 + if diff <= 0.3: + return base_target - 0.5 + elif 0.5 <= diff <= 0.8: + return base_target - 0.7 + elif 0.8 <= diff <= 1.5: + return base_target - 1.0 + elif 1.5 <= diff <= 2.5: + return base_target - 1.0 + elif diff > 2.5: + return my_current_price # 差距过大,跳过不跟价 + + + + + +class ChromeAmzone: + + mark_name = "亚马逊详情采集" + country_info = { + "英国": { + "url": "https://www.amazon.co.uk/dp/B0CJ8SNXXV", + "zip_code": "SW1A 1AA", + "mark" : "SW1A 1" + }, + "德国": { + "url": "https://www.amazon.de/dp/B0CC8CW9G2?th=1", + "zip_code": "10115" + }, + "法国": { + "url": "https://www.amazon.fr/dp/B0FRG1MJ8H?th=1", + "zip_code": "75001" + }, + "西班牙": { + "url": "https://www.amazon.es/dp/B08ZXVNYNN", + "zip_code": "28001" + }, + "意大利": { + "url": "https://www.amazon.it/dp/B0D1P17T2Q", + "zip_code": "20121" + } + } + + def __init__(self): + """ + 杀死当前谷歌浏览器进程,并使用 drissionpage 启动谷歌浏览器,使用系统安装的浏览器默认用户文件夹 + """ + # 杀死现有的Chrome进程 + print("正在关闭现有的chromium浏览器进程...") + os.system('taskkill /f /t /im chromium.exe') + time.sleep(2) + + print("正在启动chromium浏览器...") + sellersprite_plug_path = os.path.join(base_dir,"app_resource","sellersprite-extension-mv3") + # sellersprite_plug_path = os.path.join("D:\\私单交付\\maixiang_AI\\","app_resource","sellersprite-extension-mv3") + print(sellersprite_plug_path) + # 配置浏览器选项 + co = ChromiumOptions() + # co.use_system_user_path(on_off=True) + user_data_path = os.path.join(base_dir,"user_data","chrome_data") + if not os.path.exists(user_data_path): + os.makedirs(user_data_path,exist_ok=True) + co.set_user_data_path(user_data_path) + # co.set_user_data_path(r"D:\私单交付\maixiang_AI\user_data\chrome_data") + co.set_local_port(port=19897) + co.add_extension(sellersprite_plug_path) + # co.set_argument('--disable-features=DisableLoadExtensionCommandLineSwitch') + # co.set_argument('--load-extension',sellersprite_plug_path) + broswer_path = os.path.join(base_dir,"app_resource","chrome-win","chromium.exe") + co.set_browser_path(broswer_path) + # co.set_browser_path(r'D:\私单交付\maixiang_AI\app_resource\chrome-win\chromium.exe') + + # 使用系统默认的用户数据目录 + # co.set_user_data_path(r'C:\Users\{}\AppData\Local\Google\Chrome\User Data'.format(os.getenv('USERNAME'))) + self.browser = Chromium(co) + self.tab = self.browser.latest_tab + print("Chrome浏览器启动成功") + + def close_init_popup(self): + """ + 关闭所有的初始化弹窗 + """ + self.tab.wait.doc_loaded(timeout=60,raise_err=True) + footbar = self.tab.eles('xpath://footer[@class="el-dialog__footer"]',timeout=5) + if len(footbar) > 0: + do_not_remind = footbar[0].eles('xpath:.//input[@class="el-checkbox__original"]') + if len(do_not_remind) > 0: + do_not_remind[0].check() + resume_immediately = footbar[0].eles('xpath:.//button') + if len(resume_immediately) > 0: + resume_immediately[0].click() + + self.tab.wait.doc_loaded(timeout=60,raise_err=True) + accept_btn = self.tab.eles('xpath://input[@id="sp-cc-accept"]',timeout=10) + if len(accept_btn) > 0: + accept_btn[0].click() + + + def run(self, country, asin): + """ + 运行亚马逊详情采集任务 + + Args: + country: 国家名称(如:英国、德国、法国、西班牙、意大利) + asin: 亚马逊商品ASIN码 + + Returns: + dict: 包含采集到的数据 + """ + try: + # 验证国家是否支持 + if country not in self.country_info: + error_msg = f"不支持的国家: {country},支持的国家有: {list(self.country_info.keys())}" + print(error_msg) + show_notification(error_msg, "error") + return None + + # 获取国家配置 + country_config = self.country_info[country] + zip_code = country_config["zip_code"] + mark = country_config.get("mark") + + # 1. 根据国家和ASIN拼接链接 + base_url = country_config["url"] + # 提取域名部分 + domain = base_url.split("/dp/")[0] + # 拼接新的URL + product_url = f"{domain}/dp/{asin}" + print(f"正在访问: {product_url}") + + # 打开链接 + self.tab.get(product_url) + time.sleep(3) # 等待页面初步加载 + self.tab.wait.doc_loaded(timeout=30, raise_err=False) + + self.close_init_popup() + # 2. 切换国家/设置邮编 + print(f"正在检查并设置邮编: {zip_code},标识: {mark}") + self._set_zip_code(zip_code,mark) + + self.tab.wait.doc_loaded(timeout=5,raise_err=False) + + + # 3. 抓取数据 + print("正在抓取商品数据...") + data = self._scrape_data() + + # 添加基本信息 + data['country'] = country + data['asin'] = asin + data['url'] = product_url + data['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + + print(f"数据抓取完成: {json.dumps(data)}") + return data + + except Exception as e: + error_msg = f"运行出错: {traceback.format_exc()}" + print(error_msg) + show_notification(f"采集失败: {str(e)}", "error") + return None + + def _set_zip_code(self, zip_code,mark=None): + """ + 设置邮编 + + Args: + zip_code: 目标邮编 + """ + try: + # 检查当前邮编 + zip_display = self.tab.ele('xpath://div[@id="glow-ingress-block"]', timeout=10) + + if zip_display: + current_text = zip_display.text + # print(f"当前地址信息: {current_text}") + # 先检查标识 + if mark is not None and mark in current_text: + print(f"邮编检测到标识: {mark},无需修改") + return True + # 检查是否已经包含目标邮编 + if zip_code in current_text: + print(f"邮编已经设置为: {zip_code},无需修改") + return True + + # 需要设置邮编 + print(f"正在设置邮编为: {zip_code}") + + # 点击地址选择按钮 + location_link = self.tab.ele('xpath://a[@id="nav-global-location-popover-link"]', timeout=10) + if not location_link: + print("找不到地址设置按钮") + return False + + location_link.click() + time.sleep(1) + + # 等待邮编输入框出现 + zip_input = self.tab.ele('xpath://input[@id="GLUXZipUpdateInput"]', timeout=10) + if not zip_input: + print("找不到邮编输入框") + return False + + # 输入邮编 + zip_input.input(zip_code, clear=True) + time.sleep(0.5) + + # 点击提交按钮 + submit_btn = self.tab.ele('xpath://input[@aria-labelledby="GLUXZipUpdate-announce"]', timeout=10) + if not submit_btn: + print("找不到提交按钮") + return False + + submit_btn.click() + + continue_btn = self.tab.eles('xpath://div[@class="a-popover-footer"]//input[@id="GLUXConfirmClose"]',timeout=10) + if len(continue_btn) > 0: + continue_btn[0].click() + + # 等待提交按钮消失(表示请求已发送) + print("等待邮编更新...") + time.sleep(2) + + # 等待页面加载完成 + self.tab.wait.doc_loaded(timeout=30, raise_err=False) + time.sleep(2) + + # 验证邮编是否设置成功 + zip_display_after = self.tab.ele('xpath://div[@id="glow-ingress-block"]', timeout=10) + if zip_display_after: + updated_text = zip_display_after.text + # print(f"更新后的地址信息: {updated_text}") + + if zip_code in updated_text: + print(f"邮编设置成功: {zip_code}") + return True + else: + # print(f"邮编设置可能失败,当前显示: {updated_text}") + return False + + return True + + except Exception as e: + print(f"设置邮编时出错: {traceback.format_exc()}") + return False + + def _scrape_data(self): + """ + 抓取商品数据 + + Returns: + dict: 抓取到的数据 + """ + data = { + 'top_sellers': [], # 前两名卖家信息 + 'cart_seller': None # 购物车所属卖家 + } + + try: + # 等待页面加载 + time.sleep(3) + + # 1. 获取前两名卖家的价格和库存(来自 sellersprite 插件) + print("正在抓取卖家排名数据...") + surplus_tables = self.tab.eles( + 'xpath://div[@id="sellersprite-extension-Inventory-surplus-count"]//div[@class="surplus-table"]', + timeout=10 + ) + + if surplus_tables: + print(f"找到 {len(surplus_tables)} 个卖家数据") + # 只获取前两个 + for idx, table in enumerate(surplus_tables[:2]): + try: + # 提取价格和库存信息 + # 注意:需要根据实际的HTML结构调整选择器 + # print(f"第{idx+1}名卖家数据: {text_content}") + + seller_info = { + 'rank': idx + 1, + } + + # 尝试提取更结构化的数据 + # 这里需要根据实际HTML结构来解析 + # 可能需要查找子元素 + try: + # 示例:查找价格和库存的具体子节点 + price_ele = table.ele('xpath:.//span[contains(@class,"price")]', timeout=2) + stock_ele = table.ele('xpath:.//span[@class="surplus-count-num"]', timeout=2) + shop_name_ele = table.ele('xpath:.//div[@class="surplus-table-item"][2]//a', timeout=2) + + seller_info['price'] = remove_special_characters(price_ele.text.strip()) + seller_info['stock'] = remove_special_characters(stock_ele.text.strip()) + seller_info['shop_name'] = shop_name_ele.text.strip() + + except Exception as e: + print("解析出错",e) + pass + + data['top_sellers'].append(seller_info) + + except Exception as e: + print(f"解析第{idx+1}名卖家数据失败: {str(e)}") + else: + print("未找到 sellersprite 插件数据,可能插件未启用") + + # 2. 获取购物车所属卖家 + print("正在抓取购物车卖家信息...") + cart_seller = self.tab.ele( + 'xpath://div[@data-csa-c-content-id="desktop-merchant-info"]//a[@id="sellerProfileTriggerId"]', + timeout=10 + ) + + if cart_seller: + seller_name = cart_seller.text.strip() + print(f"购物车所属卖家: {seller_name}") + data['cart_seller'] = seller_name + else: + print("未找到购物车卖家信息") + # 尝试其他可能的选择器 + try: + alt_seller = self.tab.ele('xpath://a[@id="sellerProfileTriggerId"]', timeout=5) + if alt_seller: + data['cart_seller'] = alt_seller.text.strip() + print(f"购物车所属卖家(备用方式): {data['cart_seller']}") + except: + pass + + return data + + except Exception as e: + print(f"抓取数据时出错: {traceback.format_exc()}") + return data + + def close(self): + """关闭浏览器""" + try: + if self.browser: + self.browser.quit() + print("浏览器已关闭") + except Exception as e: + print(f"关闭浏览器时出错: {str(e)}") + + +class AmzonePriceMatch(AmamzonBase): + mark_name = "跟价" + + def SwitchPage(self): + """ + 切换至 管理所有库存页面 + 1、等待 //navigation-favorites-bar[@class="hydrated"] 出现 + """ + navigation = self.tab.ele('xpath://navigation-favorites-bar[@class="hydrated"]') + navigation.wait.displayed(raise_err=False) + page_btn = navigation.sr('xpath://internal-fav-bar-links[@data-internal="navigation"]').sr( + 'xpath://a[@data-page-id="ezdpc-gui-inventory-mons"]') + page_btn.wait.displayed(raise_err=False) + page_btn.click(timeout=5) + + self.tab.wait.doc_loaded() + # 等待搜索框出现 + search_region = self.tab.ele('xpath://div[@id="searchBoxContainer"]//kat-input-group') + search_region.wait.displayed(raise_err=False) + + def search(self,filter_type="ApprovalRequired"): + sku_ls = [] + + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]",timeout=5) + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + drop_down = self.tab.ele('xpath://div[contains(@class,"VolusListingStatusDropDown-module__verticalContainer")]//kat-dropdown') + drop_down.wait.displayed(raise_err=False) + drop_down.wait.enabled(raise_err=False) + time.sleep(0.6) + drop_down.click() + # //kat-option[@value="SearchSuppressed"] + xp = f'xpath://kat-option[@value="{filter_type}"]' + print(f"【{self.mark_name}】正在寻找筛选条件 {filter_type},xpath: {xp}") + approval_required = self.tab.eles(xp,timeout=5) + if len(approval_required) == 0: + print(f"【{self.mark_name}】没有需要{filter_type}选项】没有需要{filter_type}的商品了") + return sku_ls # "没有需要审批的商品了" + else: + approval_required = approval_required[0] + approval_required.wait.displayed(raise_err=False) + approval_required.click() + + approval_required_text = approval_required.text + print(f"【{self.mark_name}】已选择筛选条件: {approval_required_text}") + + count = re.findall(r'\d+', approval_required_text) + if count: + count = int(count[0]) + print(f"【{self.mark_name}】待审批的商品数量: {count}") + if count <= 0: + print(f"【{self.mark_name}】没有需要{filter_type}的商品了") + return sku_ls #"没有需要审批的商品了" + for _ in range(3): + # 等待加载完成 + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]") + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + sku_ls = self.tab.eles("xpath://div[@data-sku]",timeout=3) + if len(sku_ls) > 0: + break + approval_required.click() + return sku_ls + + def search_asin(self, asin): + search_region = self.tab.ele('xpath://div[@id="searchBoxContainer"]//kat-input-group') + search_region.wait.displayed(raise_err=False) + time.sleep(0.6) + search_input = self.tab.ele("xpath://kat-input[contains(@class,'SearchBox-module__searchInput')]").sr( + 'xpath://span[@class="container"]//input[@part="input"]') + search_input.input(asin,clear=True) + sku_ls = [] + for _ in range(3): + search_btn = self.tab.ele("xpath://kat-icon[@name='search']") + search_btn.click() + + load_ele = self.tab.ele("xpath://div[contains(@class,'Loader-module__loader')]") + # load_ele.wait.hidden(timeout=3, raise_err=False) + load_ele.wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + sku_ls = self.tab.eles("xpath://div[@data-sku]",timeout=3) + if len(sku_ls) > 0: + break + return sku_ls + + def search_asin_action(self,asin:str): + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]", timeout=5) + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + sku_ls = self.search_asin(asin=asin) + print(f"【{self.mark_name}】{asin} 搜索到 {len(sku_ls)} 个SKU") + + def run_page_action(self,chrome:ChromeAmzone,current_shop_name:str,appoint_asin:str=None,skip_asin:list=[]): + print(f"【{self.mark_name}】,开始执行") + num = 0 + retry_num = 0 + already_asin = set() + get_page_faild = 0 + #获取当前国家 + current_country_ele = self.tab.ele('xpath://div[@class="dropdown-account-switcher-header-label"]/span[last()]', + timeout=20) + current_country = current_country_ele.text.strip() + + while retry_num < 3: # 最多重试3次 + try: + if appoint_asin is not None: + print(self.mark_name,"指定asin操作",appoint_asin) + self.search_asin_action(asin=appoint_asin) + + load_ele = self.tab.eles("xpath://div[contains(@class,'Loader-module__loader')]", timeout=5) + if len(load_ele) > 0: + load_ele[0].wait.deleted(timeout=3, raise_err=False) + time.sleep(0.5) + + # 获取当前页码 + try: + page_pamel = self.tab.eles('xpath://kat-pagination', timeout=5) + if len(page_pamel) > 0: + current_page = page_pamel[0].sr('xpath:.//ul[@class="pages"]//li[@aria-current="true"]').text + + # 总页数 + total_page = page_pamel[0].sr.eles( + 'xpath:.//ul[@class="pages"]//span[@class="page__inner"][last()]') + if len(total_page) > 0: + total_page = total_page[-1].text + else: + total_page = 0 + print(f"【{self.mark_name}】当前页码: {current_page} / 总页数: {total_page}") + get_page_faild = 0 + except Exception as e: + print("【{self.mark_name}】","获取页码失败", e) + get_page_faild += 1 + if get_page_faild > 2: + show_notification(f"【{self.mark_name}】获取页码失败超3次停止任务!") + break + + sku_ls = self.tab.eles("xpath://div[@data-sku]", timeout=10) + print(f"【{self.mark_name}】获取到 {len(sku_ls)}") + # for sku_ele in sku_ls[0:2]: + for sku_ele in sku_ls: + + asin = sku_ele.ele( + 'xpath:.//div[contains(@class,"JanusSplitBox-module__container")]//div[contains(@class,"JanusSplitBox-module__panel--") and contains(string(.),"ASIN")]/..//div[last()]', + timeout=3).text + print(f"【{self.mark_name}】ASIN {asin} 找到....") + if asin in already_asin: + print(f"【{self.mark_name}】{asin} 已经处理过了,跳过") + continue + if asin in skip_asin: + yield (asin, { + "statu": "跳过,需要跳过的ASIN" + }) + continue + bottom_price_ele = sku_ele.eles('xpath:.//div[@data-test-id="LowestPrice"]/div[2]',timeout=5) + bottom_price = "" #初始化为空 + if len(bottom_price_ele) > 0: + try: + bottom_price_text = bottom_price_ele[0].text + # print("最低价格->>",bottom_price_text) + bottom_price = f"{sum(split_currency_values(bottom_price_text))}" + except Exception as e: + print("最低价提取失败",e) + current_price_ele = sku_ele.eles('xpath:.//b[text()="价格"]/../..//kat-input',timeout=5) + if len(current_price_ele) > 0: + current_price = current_price_ele[0].attr("value") + else: + print(f"{self.mark_name} 没有获取到当前价格") + yield (asin, { + "statu": "失败(没有获取到当前的价格)" + }) + continue + front_end_data = chrome.run(country=current_country,asin=asin) + print(self.mark_name,"亚马逊前台抓取到数据",front_end_data) + # + cart_seller = front_end_data.get("cart_seller") + if cart_seller == current_shop_name and len(front_end_data.get("top_sellers"))< 2: + yield (asin, { + "statu": "跳过(自己的购物车,只有第一名)", + "currentPrice": current_price, + }) + continue + + recommend_price_ele= sku_ele.eles('xpath:.//div[@data-test-id="FeaturedOfferPrice"]/div[2]',timeout=5) + if len(recommend_price_ele) > 0: + try: + price_text = recommend_price_ele[0].text + # print("推荐价格 ->>",price_text) + recommend_price,shipping_fee = split_currency_values(price_text) + except Exception as e: + print("推荐价格和运费提取失败 ->>",e) + recommend_price, shipping_fee = 0, 0 + else: + print(f"{self.mark_name} 没有查找有推荐价格和运费") + recommend_price,shipping_fee = 0,0 + + adjust_prices = calculate_target_price( + front_end_data, float(current_price), current_shop_name, + recommend_price, shipping_fee + ) + print(asin,"-->>",f"【逻辑计算后的价格】",adjust_prices) + if adjust_prices is not None: + #修改价格 + current_price_ele[0].input(f"{adjust_prices}",clear=True) + out_focus = sku_ele.ele('xpath:.//b[text()="价格"]/../..//kat-label',timeout=5) + out_focus.click() + + save_all_btn = self.tab.ele('xpath://kat-button[@label="保存所有"]', timeout=10) + save_all_btn.wait.displayed(timeout=10, raise_err=False) + save_all_btn.click() + save_all_btn.wait.deleted(timeout=10, raise_err=False) + recommendedPrice = recommend_price + shipping_fee + price_1 = float(front_end_data.get("top_sellers")[0].get("price")) # 实际第一名价格 + price_2 = float(front_end_data.get("top_sellers")[1].get("price")) if len(front_end_data.get("top_sellers")) >= 2 else "" # 实际第二名价格 + cartShopName = front_end_data.get("cart_seller") + yield (asin,{ + "statu" : "改价成功", + "currentPrice" : current_price, + "recommendedPrice" : f"{recommendedPrice}", + "minimumPrice" : bottom_price, #最低价格 + "firstPlace": price_1, + "secondPlace": price_2, + "cartShopName" : cartShopName, + "priceChangeStatus" : "改价成功", + }) + except Exception as e: + print(f"【{self.mark_name}】处理跟价操作异常", e) + traceback.print_exc() + retry_num += 1 + self.tab.refresh() + self.tab.wait.doc_loaded(raise_err=False, timeout=120) + +class PriceTask: + country_info = { + "DE": "德国", + "FR": "法国", + "ES": "西班牙", + "IT": "意大利", + "UK": "英国" + } + + def __init__(self, user_info: dict = None): + """初始化审批任务处理器 + + Args: + user_info: 用户信息字典,包含 company, username, password + """ + self.user_info = user_info or {} + self.running = True + + def log(self, message: str, level: str = "INFO"): + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + if level == "ERROR": + show_notification(message, "error") + print(f"[{timestamp}] [PriceTask] [{level}] {message}") + + def process_task(self, task_data: dict): + """处理审批任务主入口 + + Args: + task_data: 任务数据 + """ + try: + data = task_data.get("data", {}) + task_id = data.get("task_id") + # items = data.get("items", []) + shop_name = data.get("shop_name") + country_codes = data.get("country_codes", []) + risk_listing_filter = data.get("risk_listing_filter", "Active") + user_id = data.get("user_id") + stage_index = data.get("stage_index") + final_stage = bool(data.get("final_stage", True)) + + # 用于测试 + limit = data.get("limit", None) + + if not task_id: + self.log("任务ID为空,跳过", "WARNING") + return + + # if not items: + # self.log("店铺列表为空,跳过", "WARNING") + # return + + if not country_codes: + self.log("国家列表为空,跳过", "WARNING") + return + + self.log(f"开始处理审批任务 {task_id},共 1 个店铺,{len(country_codes)} 个国家") + + from config import runing_task + runing_task[task_id] = { + "status": "running", + "start_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "total_shops": 1, + "processed_shops": 0, + "total_countries": len(country_codes) , + "processed_countries": 0, + "total_asins": 0, + "processed_asins": 0, + "success_count": 0, + "failed_count": 0, + "stop_requested": False + } + + # 检查是否收到暂停请求 + if task_id in runing_task and runing_task[task_id].get("stop_requested", False): + self.log(f"检测到任务 {task_id} 的暂停请求,停止处理", "WARNING") + runing_task[task_id]["status"] = "stopped" + return + + self.log(f"开始处理店铺: {shop_name}") + show_notification(f"开始处理店铺: {shop_name}", "info") + + try: + self.process_shop(data, country_codes, task_id, risk_listing_filter, user_id, stage_index, + final_stage, limit=limit) + + # self.process_shop(shop_item, country_codes, task_id,risk_listing_filter) + # 更新已处理店铺数 + if task_id in runing_task: + runing_task[task_id]["processed_shops"] += 1 + except Exception as e: + import traceback + self.log(f"处理店铺 {shop_name} 失败: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + # 更新任务状态 + if task_id in runing_task: + if runing_task[task_id].get("stop_requested", False): + runing_task[task_id]["status"] = "stopped" + self.log(f"任务 {task_id} 已被暂停!") + else: + runing_task[task_id]["status"] = "completed" + self.log(f"任务 {task_id} 处理完成!") + + except Exception as e: + import traceback + self.log(f"任务处理失败: {traceback.format_exc()}", "ERROR") + if task_id: + from config import runing_task + if task_id in runing_task: + runing_task[task_id]["status"] = "failed" + runing_task[task_id]["error"] = str(e) + + # def process_shop(self, shop_item: dict, country_codes: list, task_id: int, risk_listing_filter: str): + def process_shop(self, shop_item: dict, country_codes: list, task_id: int, risk_listing_filter: str, + user_id=None, stage_index=None, final_stage: bool = True, limit: str = None): + """处理单个店铺 + + Args: + shop_item: 店铺信息 + country_codes: 国家代码列表 + task_id: 任务ID + risk_listing_filter: 风险商品筛选条件 + """ + shop_name = shop_item.get("shopName", "未知店铺") + company_name = shop_item.get("companyName", "") + shopMallName = shop_item.get("shopMallName","") + skip_asins_by_country = shop_item.get("skip_asins_by_country",{}) + asin_rows_by_country = shop_item.get("asin_rows_by_country",{}) + + if not company_name: + self.log(f"店铺 {shop_name} 的公司名称为空,跳过", "WARNING") + return + + if task_id in runing_task: + runing_task[task_id]["current_shop"] = shop_name + + # 将店铺添加到正在执行中的店铺列表 + start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + runing_shop[shop_name] = start_time + self.log(f"店铺 {shop_name} 已添加到执行列表,账号: {company_name},开始时间: {start_time}") + + # 店铺打开重试最多3次 + driver = None + max_retries = 3 + + error_info = "" + for retry in range(max_retries): + try: + self.log(f"尝试打开店铺 {shop_name} (第 {retry + 1}/{max_retries} 次)") + + # 如果不是第一次尝试,先杀进程 + # if retry > 0: + # self.log("重试前先杀掉浏览器进程...") + # kill_process("v6") + # kill_process("v5") + # time.sleep(2) + + # 组装用户信息并创建驱动 + user_info = { + **self.user_info, + "company": company_name + } + driver = AmzonePriceMatch(user_info) + browser = driver.open_shop(shop_name) + + if browser and browser != "店铺不存在": + self.log(f"成功打开店铺 {shop_name}") + else: + self.log(f"打开店铺失败: {browser}", "WARNING") + driver = None + continue + + # 判断是否需要登录 + need_login = driver.need_login() + print("【是否需要登录】:", need_login) + if need_login: + self.log(f"店铺 {shop_name} 需要登录,正在登录...") + # 获取店铺凭证 + response = get_shop_info(shop_name) + print("【获取店铺凭证返回】:", response.text) + shop_data = response.json() + if not shop_data: + mes = f"获取店铺凭证失败,响应数据: {shop_data.get('message', '未知错误')}" + self.log(mes, "ERROR") + show_notification(mes, "ERROR") + continue + + password = shop_data["data"]["password"] + + login_success = driver.login(password) + if login_success: + self.log(f"店铺 {shop_name} 登录成功,正在重新打开店铺...") + browser = driver.open_shop(shop_name) + if browser and browser != "店铺不存在": + self.log(f"成功打开店铺 {shop_name} 登录后") + break + else: + self.log(f"登录后打开店铺失败: {browser}", "WARNING") + driver = None + else: + self.log(f"店铺 {shop_name} 登录失败", "WARNING") + driver = None + else: + break + + except Exception as e: + import traceback + self.log(f"打开店铺异常: {traceback.format_exc()}", "INFO") + driver = None + error_info = str(e) + time.sleep(10) + + # 如果还有重试机会,等待后继续 + if retry < max_retries - 1: + time.sleep(3) + + # 检查是否成功打开 + if not driver or not browser or browser == "店铺不存在": + error_msg = f"店铺 {shop_name} 打开失败,已重试 {max_retries} 次,跳过该店铺,{error_info}" + self.log(error_msg, "ERROR") + # 从执行列表中移除 + if shop_name in runing_shop: + del runing_shop[shop_name] + return + + try: + # 处理每个国家 + for country_code in country_codes: + # 检查是否收到暂停请求 + if task_id in runing_task and runing_task[task_id].get("stop_requested", False): + self.log(f"检测到任务 {task_id} 的暂停请求,停止处理国家", "WARNING") + break + skip_asin = skip_asins_by_country.get(country_code,[]) #需要跳过的asin + appoint_asin = asin_rows_by_country.get(country_code,[]) + try: + self.process_country(driver, country_code, task_id, shop_name, risk_listing_filter, + shopMallName=shopMallName,skip_asin=skip_asin, limit=limit,appoint_asin=appoint_asin) + except Exception as e: + import traceback + self.log(f"处理国家 {country_code} 失败: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + # 最后回传,标记完成 + try: + # self.post_result(task_id, shop_name, country_code, "", "", is_done=True) + if final_stage: + self.post_result(task_id, shop_name, country_code, "", {},shopMallName,is_done=True) + else: + self.post_stage_finished(task_id, user_id, stage_index) + except Exception as e: + self.log(f"回传结果失败: {str(e)}", "ERROR") + finally: + # 关闭店铺 + try: + if driver: + self.log(f"关闭店铺 {shop_name}") + driver.close_store() + time.sleep(2) + except Exception as e: + self.log(f"关闭店铺失败: {str(e)}", "WARNING") + + # 从正在执行中的店铺列表中移除 + if shop_name in runing_shop: + del runing_shop[shop_name] + self.log(f"店铺 {shop_name} 已从执行列表中移除") + + def process_country(self, driver: AmzonePriceMatch, country_code: str, task_id: int, shop_name: str, + risk_listing_filter: str,shopMallName:str,skip_asin:list,appoint_asin:list,limit: str = None): + """处理单个国家的审批任务 + + Args: + driver: AmzoneApprove驱动实例 + country_code: 国家代码(如 UK, DE, FR 等) + task_id: 任务ID + shop_name: 店铺名称 + risk_listing_filter: 风险商品筛选条件 + """ + + # 转换国家代码为中文名称 + country_name = self.country_info.get(country_code, country_code) + info_mes = f"开始处理国家: {country_name} ({country_code}),需要跳过的asin {skip_asin}" + self.log(info_mes) + show_notification(info_mes, "info") + + # 更新当前处理的国家 + if task_id in runing_task: + runing_task[task_id]["current_country"] = country_name + + # 切换国家,最多重试3次 + max_retries = 3 + switch_success = False + + for retry in range(max_retries): + try: + self.log(f"尝试切换到国家 {country_name} (第 {retry + 1}/{max_retries} 次)") + + # 如果不是第一次尝试,先刷新页面 + if retry > 0: + self.log("重试前刷新页面...") + try: + driver.tab.refresh() + time.sleep(3) + except Exception as e: + self.log(f"刷新页面失败: {str(e)}", "WARNING") + + switch_success = driver.SwitchingCountries(country_name) + if switch_success: + self.log(f"成功切换到国家 {country_name}") + break + else: + self.log(f"切换到国家 {country_name} 失败", "WARNING") + + except Exception as e: + import traceback + self.log(f"切换国家 {country_name} 异常: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + # 如果还有重试机会,等待后继续 + if retry < max_retries - 1: + time.sleep(2) + + # 如果切换失败,直接返回 + if not switch_success: + error_message = f"切换到国家 {country_name} 失败,已重试 {max_retries} 次,跳过该国家" + self.log(error_message, "ERROR") + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + return + + # 切换到库存管理页面 + for retry in range(max_retries): + try: + driver.SwitchPage() + self.log(f"已切换到库存管理页面") + except Exception as e: + import traceback + self.log(f"切换页面失败: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + if retry >= max_retries-1: + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + self.log(f"切换页面失败重试退出", "ERROR") + return + + # 搜索需要审批的商品,最多重试3次 + sku_ls = [] + for retry in range(max_retries): + try: + self.log(f"尝试搜索匹配操作商品 (第 {retry + 1}/{max_retries} 次)") + sku_ls = driver.search(filter_type=risk_listing_filter) + break + except Exception as e: + self.log(f"搜索商品异常: {str(e)}", "ERROR") + if retry < max_retries - 1: + try: + driver.tab.refresh() + time.sleep(3) + except Exception as refresh_error: + self.log(f"刷新页面失败: {str(refresh_error)}", "WARNING") + + # 如果没有需要审批的商品,直接返回 + if len(sku_ls) == 0: + self.log(f"国家 {country_name} 没有搜索出的商品") + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + return + + self.log(f"国家 {country_name} 搜索出 {len(sku_ls)} 商品,开始处理...") + chrome = None + for _ in range(3): + try: + chrome = ChromeAmzone() + break + except Exception as e: + print("启动谷歌浏览器失败",e) + if chrome is None: + self.log(f"启动谷歌浏览器失败,跳过执行国家:{country_name}","ERROR") + return + + # 处理所有需要审批的商品(通过yield获取结果) + try: + # 指定 asin + max_range = max(1,len(appoint_asin)) + for i in range(max_range): + if len(appoint_asin) > i: + _shopMallName = appoint_asin[i]["shopMallName"] + ap_asin = appoint_asin[i]["shopMallName"] + else: + _shopMallName = shopMallName + ap_asin = None + + for asin, status in driver.run_page_action( + chrome = chrome, current_shop_name=_shopMallName, + appoint_asin=ap_asin,skip_asin=skip_asin + ): + # 检查是否收到暂停请求 + if task_id in runing_task and runing_task[task_id].get("stop_requested", False): + self.log(f"检测到任务 {task_id} 的暂停请求,停止处理ASIN", "WARNING") + break + + self.log(f"ASIN {asin} 处理结果: {status}") + + # 更新任务状态 + if task_id in runing_task: + runing_task[task_id]["current_asin"] = asin + runing_task[task_id]["processed_asins"] += 1 + + runing_task[task_id]["failed_count"] += 1 + + # 回传结果到API + try: + self.post_result(task_id, shop_name, country_code, asin, status,shopMallName) + except Exception as e: + self.log(f"回传结果失败: {str(e)}", "ERROR") + + except Exception as e: + import traceback + self.log(f"处理审批商品异常: {str(e)}", "ERROR") + self.log(traceback.format_exc(), "ERROR") + + # 更新已处理国家数 + if task_id in runing_task: + runing_task[task_id]["processed_countries"] += 1 + + try: + chrome.close() + except Exception as e: + print("退出谷歌浏览器失败",e) + os.system('taskkill /f /t /im chromium.exe') + + self.log(f"国家 {country_name} 处理完成") + + def post_stage_finished(self, task_id: int, user_id, stage_index): + import requests + from config import DELETE_BRAND_API_BASE + + if user_id in (None, "", 0): + raise ValueError("user_id is required for stage completion callback") + if stage_index is None: + raise ValueError("stage_index is required for stage completion callback") + + url = f"{DELETE_BRAND_API_BASE}/api/shop-match/tasks/{task_id}/stage-finished" + payload = {"stage_index": stage_index} + params = {"user_id": user_id} + + max_retries = 3 + for retry in range(max_retries): + try: + self.log(f"Attempting stage completion callback ({retry + 1}/{max_retries})") + response = requests.post( + url, + params=params, + json=payload, + headers={"Content-Type": "application/json"}, + timeout=30, + verify=False, + ) + self.log(f"Stage completion callback response: {response.text}") + data = response.json() if response.text else {} + if response.status_code == 200 and isinstance(data, dict) and data.get("success"): + self.log(f"Stage completion callback succeeded: task={task_id}, stage={stage_index}") + return + self.log(f"Stage completion callback failed, status={response.status_code}", "WARNING") + except Exception as e: + self.log(f"Stage completion callback exception: {str(e)}", "ERROR") + if retry < max_retries - 1: + time.sleep(2) + + raise RuntimeError(f"Stage completion callback failed after retries: task={task_id}, stage={stage_index}") + + def post_result(self, task_id: int, shop_name: str, country_code: str, asin: str, status: dict,shopMallName:str, + is_done: bool = False): + """回传处理结果到API + + Args: + task_id: 任务ID + shop_name: 店铺名称 + country_code: 国家代码 + asin: ASIN + status: 处理状态 + """ + + url = f"{DELETE_BRAND_API_BASE}/api/price-track/tasks/{task_id}/result" + """ + (asin,{ + "statu" : "改价成功", + "currentPrice" : current_price, + "recommendedPrice" : f"{recommendedPrice}", + "minimumPrice" : bottom_price, #最低价格 + "firstPlace": price_1, + "secondPlace": price_2, + "cartShopName" : current_shop_name, + "priceChangeStatus" : "改价成功", + }) + """ + + payload = { + "shops": [ + { + "shopName": shop_name, + "countries": { + "additionalProperties1": [ + { + "shopMallName": shopMallName, + "asin": asin, + "price": status.get("currentPrice") if status.get("currentPrice") else "", + "recommendedPrice": status.get("recommendedPrice") if status.get("recommendedPrice") else "", + "minimumPrice": status.get("minimumPrice") if status.get("minimumPrice") else "", + "firstPlace": status.get("firstPlace") if status.get("firstPlace") else "", + "secondPlace": status.get("secondPlace") if status.get("secondPlace") else "", + "cartShopName": status.get("cartShopName") if status.get("cartShopName") else "", + "priceChangeStatus": "UPDATED", + # "modifyCount": "2", + "status": status.get("statu") + } + ] + }, + "error": "" + } + ] + } + if is_done: + payload["shops"][0]["success"] = is_done + + max_retries = 3 + for retry in range(max_retries): + try: + print("================【跟价】=====================") + self.log(f"尝试回传结果 (第 {retry + 1}/{max_retries} 次)") + self.log(f"回传URL: {url}") + self.log(f"回传数据: {payload}") + response = requests.post( + url, + json=payload, + headers={"Content-Type": "application/json"}, + timeout=30, + verify=False + ) + self.log(f"回传结果: {response.text}") + data = response.json() if response.text else {} + if response.status_code == 200 and isinstance(data, dict) and data.get("success"): + self.log(f"结果回传成功: {asin} - {status}") + return + else: + self.log(f"结果回传失败,状态码: {response.status_code}", "WARNING") + print("=====================================") + + except Exception as e: + self.log(f"调用API异常: {str(e)}", "ERROR") + print("=====================================") + + # 如果还有重试机会,等待后继续 + if retry < max_retries - 1: + time.sleep(2) + + self.log(f"已达到最大重试次数,结果回传最终失败", "ERROR") + raise RuntimeError("已达到最大重试次数,结果回传最终失败") + + +if __name__ == '__main__': + # 使用示例 + print("=" * 50) + print("亚马逊详情采集示例") + print("=" * 50) + + try: + # 创建ChromeAmzone实例 + chrome = ChromeAmzone() + + # 示例1:采集英国站点的商品信息 + print("\n示例1:采集英国站点商品") + result1 = chrome.run(country="英国", asin="B0CJ8SNXXV") + if result1: + print(f"采集成功: {result1}") + + # 示例2:采集德国站点的商品信息 + # print("\n示例2:采集德国站点商品") + # result2 = chrome.run(country="德国", asin="B0CC8CW9G2") + # if result2: + # print(f"采集成功: {result2}") + + # # 关闭浏览器 + # print("\n正在关闭浏览器...") + # chrome.close() + + except Exception as e: + print(f"运行出错: {traceback.format_exc()}") + + + diff --git a/app/amazon/tool.py b/app/amazon/tool.py index af48ded..dd9eeb8 100644 --- a/app/amazon/tool.py +++ b/app/amazon/tool.py @@ -7,6 +7,7 @@ except ImportError: import requests from urllib.parse import quote +import re def show_notification(message: str, message_type: str = "error"): @@ -112,5 +113,50 @@ def get_shop_info(shop_name: str, base_url: str = "http://8.136.19.173:18080") - +def remove_special_characters(text: str) -> str: + """ + 去除字符串中的特殊字符,只保留数字、小数点和负号。 + 例如:'£24.55' -> '24.55' + """ + # 匹配所有允许的字符:数字、小数点、负号 + # 注意:负号必须位于开头才合法,但这里只做字符保留,不做格式校验 + cleaned = re.sub(r'[^0-9.-]', '', text) + return cleaned + +def split_currency_values(currency_str: str) -> tuple[float, float]: + """ + 将包含两个货币值的字符串拆分成两个浮点数。 + 参数: + currency_str (str): 格式如 "€22.64 + €0.00" 的字符串,中间以 '+' 分隔, + 每部分可包含任意货币符号或前缀/后缀。 + 返回: + tuple[float, float]: 两个数值,顺序与字符串中的出现顺序一致。 + 异常: + ValueError: 如果字符串不包含正好两个部分,或者任一部分中无法提取到数值。 + """ + # 按第一个 '+' 分割,最多分为两部分 + parts = currency_str.split('+', 1) + if len(parts) != 2: + raise ValueError("字符串必须包含两个由 '+' 分隔的部分") + + # 匹配整数或浮点数(可选负号) + number_pattern = r'-?\d+(?:\.\d+)?' + values = [] + + for part in parts: + # 去除首尾空格 + part = part.strip() + match = re.search(number_pattern, part) + if not match: + raise ValueError(f"无法从 '{part}' 中提取数值") + values.append(float(match.group())) + + return tuple(values) + + +if __name__ == '__main__': + cu_str = "€58.44 + €0.00 匹配" + res = split_currency_values(cu_str) + print(sum(res)) \ No newline at end of file