"""Download real dish images from 下厨房 for all 69 dishes.""" import json, os, re, time, random, requests DIR = os.path.dirname(os.path.abspath(__file__)) IMAGES = os.path.join(DIR, 'images') os.makedirs(IMAGES, exist_ok=True) with open(os.path.join(DIR, 'dishes.json'), 'r', encoding='utf-8') as f: dishes = json.load(f) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', } done = 0 fail = 0 none = 0 total = len(dishes) for d in dishes: name = d['菜名'] dish_id = d['id'] fname = f'dish_{dish_id}.jpg' fpath = os.path.join(IMAGES, fname) # Skip if already downloaded if os.path.exists(fpath): done += 1 continue print(f'[{done+fail+none+1}/{total}] {name} ...', end=' ', flush=True) try: resp = requests.get('https://www.xiachufang.com/search/', params={'keyword': name}, headers=headers, timeout=15) imgs = re.findall(r'https?://i\d\.chuimg\.com/[a-f0-9]+_\d+w_\d+h\.jpg', resp.text) if not imgs: # Try PNG too imgs = re.findall(r'https?://i\d\.chuimg\.com/[a-f0-9]+_\d+w_\d+h\.(?:jpg|png|webp)', resp.text) if imgs: img_url = imgs[0] img_resp = requests.get(img_url, headers=headers, timeout=15) if img_resp.status_code == 200 and len(img_resp.content) > 5000: with open(fpath, 'wb') as f: f.write(img_resp.content) print(f'OK ({len(img_resp.content)//1024}KB)') done += 1 else: print(f'SKIP (HTTP {img_resp.status_code}, {len(img_resp.content)}B)') fail += 1 else: print('NONE') none += 1 except Exception as e: print(f'ERR: {e}') fail += 1 time.sleep(1.5 + random.random() * 2) print(f'\n=== 完成 ===') print(f'成功: {done} 失败: {fail} 未找到: {none} 总计: {total}')