如何在不暂停价格追踪循环的前提下动态添加亚马逊商品URL?
我来帮你搞定这个问题!你现在的程序没法在追踪过程中添加新商品,核心原因是单线程被while True的追踪循环占满了,根本腾不出手处理用户输入。咱们用多线程就能让价格追踪和商品添加两个任务并行执行,实现不用暂停程序就能加新商品的需求。
先给你梳理下原代码里的几个小问题,再给出完整的修改方案:
trackAndadd方法里用了未定义的url变量,应该用实例自身保存的URL- 用
eval('i.trackAndadd()')完全没必要,直接调用方法更安全高效 - 缺少容错处理,网络波动或页面结构变化会直接导致程序崩溃
完整解决方案代码
import requests import lxml from bs4 import BeautifulSoup import re import time import threading class PriceTrack: productMethods = [] def __init__(self, url): self.url = url # 保存商品URL到实例属性,方便后续追踪使用 HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) try: source = requests.get(url, headers=HEADERS).text soup = BeautifulSoup(source, 'lxml') # 解析商品标题,增加容错 title = soup.find(id='productTitle') self.ProductTitle = title.get_text().strip() if title else "未知商品" # 解析价格,处理异常情况 price_element = soup.find(id='priceblock_ourprice') if price_element: price_text = price_element.text[2:] result = re.sub(r"[,₹]", "", price_text, flags=re.I) price_part, _ = result.split('.') self.Price = float(price_part) else: self.Price = 0.0 print(f"⚠️ 警告:商品 {self.ProductTitle} 无法获取当前价格") # 初始化价格列表 self.PriceList = [self.Price] print(f"✅ 已添加商品:{self.ProductTitle},当前价格:{self.Price}") except Exception as e: print(f"❌ 添加商品失败:{str(e)}") raise def trackAndadd(self): HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) try: source = requests.get(self.url, headers=HEADERS).text soup = BeautifulSoup(source, 'lxml') price_element = soup.find(id='priceblock_ourprice') if not price_element: return price_text = price_element.text[2:] result = re.sub(r"[,₹]", "", price_text, flags=re.I) price_part, _ = result.split('.') current_price = float(price_part) # 价格变化时更新并通知 if current_price != self.PriceList[-1]: self.PriceList.append(current_price) print(f"\n📈 【价格变动】商品:{self.ProductTitle}") print(f"历史价格记录:{self.PriceList}") print(f"当前最新价格:{current_price}\n") except Exception as e: print(f"❌ 追踪商品 {self.ProductTitle} 时出错:{str(e)}") @classmethod def Addproduct(cls, url): try: product = cls(url) cls.productMethods.append(product) except Exception as e: print(f"❌ 添加商品失败:{str(e)}") def tracking_thread(): """后台追踪线程:循环更新所有商品价格""" while True: for product in PriceTrack.productMethods: product.trackAndadd() time.sleep(5) # 单个商品追踪间隔5秒 time.sleep(2) # 一轮追踪完成后稍作休息 def input_thread(): """用户输入线程:持续监听新商品URL输入""" while True: print("\n请输入要添加的亚马逊商品URL(输入'exit'可退出程序):") url = input().strip() if url.lower() == 'exit': print("程序正在退出...") exit() if url: PriceTrack.Addproduct(url) if __name__ == "__main__": # 初始化初始商品(也可以跳过,直接启动线程后再添加) print("请输入初始商品URL(按回车跳过):") url1 = input().strip() if url1: PriceTrack.Addproduct(url1) url2 = input().strip() if url2: PriceTrack.Addproduct(url2) # 启动后台追踪线程(守护线程,主线程退出时自动终止) threading.Thread(target=tracking_thread, daemon=True).start() # 主线程处理用户输入 input_thread()
关键改动说明
多线程拆分任务
- 把价格追踪逻辑放到
tracking_thread后台线程,用daemon=True标记为守护线程,这样主线程退出时它会自动结束 - 用户输入逻辑放到
input_thread作为主线程,负责和用户交互接收新URL
- 把价格追踪逻辑放到
修复核心错误
- 在
__init__中保存self.url,让每个商品实例拥有自己的URL,解决原代码中trackAndadd方法找不到url的问题 - 移除了不必要的
eval调用,直接调用product.trackAndadd()更安全高效
- 在
增加容错与体验优化
- 加入
try-except块处理网络异常、页面解析失败等情况,避免程序直接崩溃 - 增加价格变动的清晰提示,以及退出选项,提升用户体验
- 加入
现在运行程序后,你就能在后台持续追踪商品价格的同时,随时输入新的商品URL添加到追踪列表,完全不需要暂停程序啦!
内容的提问来源于stack exchange,提问作者ZeroAutumn
相关产品推荐
相关产品推荐

