如何整合Python代码遍历Excel UPC列表拼接URL实现循环请求产品数据
整合实现完整代码
import requests import json import pandas as pd import time def get_upc_info(upc_code): headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Accept-Encoding': 'gzip,deflate', } try: resp = requests.get(f'https://api.upcitemdb.com/prod/trial/lookup?upc={upc_code}', headers=headers, timeout=10) resp.raise_for_status() data = json.loads(resp.text) if 'items' not in data or len(data['items']) == 0: print(f"UPC:{upc_code} 未查询到对应商品信息") return for item in data['items']: print("{}\t{}\t{}\t{}-{}".format(item['ean'], item['title'], item['brand'], item['lowest_recorded_price'], item['highest_recorded_price'])) for offer in item['offers']: print("{}\t{}\t{}".format(offer['domain'], offer['title'], offer['price'])) print("-"*50) except Exception as e: print(f"UPC:{upc_code} 处理失败,错误信息:{str(e)}") if __name__ == '__main__': xl = pd.ExcelFile("C:/Users/Cody Sparrow/Desktop/Collection.xlsx") df = xl.parse("Sheet1") for i in df.index: current_upc = str(df.loc[i, 'Barcode']) print(f"正在处理第{i+1}条UPC:{current_upc}") get_upc_info(current_upc) # 可根据接口限流要求调整休眠时间,避免请求被拦截 time.sleep(1)
关键调整说明
- 补充了原Excel读取代码缺失的
import pandas as pd导入语句,同时修正了循环取值逻辑:原代码print(df['Barcode'])会每次打印整列UPC,改为取当前行的单个UPC值df.loc[i, 'Barcode'] - 将UPC爬取逻辑封装为独立函数,适配循环调用场景
- 增加了基础异常处理,避免请求超时、UPC无效、返回数据结构异常时程序直接崩溃
- 新增了请求间隔控制,避免短时间请求过多触发接口限流规则
内容的提问来源于stack exchange,提问作者Cody Arnold
相关产品推荐
相关产品推荐

