import requests import re import json headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' } url = 'https://movie.douban.com/top250' response = requests.get(url, headers=headers) html = response.text title_pattern = r'([^<&]+)' rating_pattern = r']*>(\d+\.?\d*)' quote_pattern = r'([^<]+)' titles = re.findall(title_pattern, html) ratings = re.findall(rating_pattern, html) quotes = re.findall(quote_pattern, html) movies = [] title_index = 0 for i in range(10): # 跳过英文名(带/的) while title_index < len(titles) and titles[title_index].startswith('/'): title_index += 1 movie = { 'rank': i + 1, 'title': titles[title_index] if title_index < len(titles) else '', 'en_title': '', 'rating': ratings[i] if i < len(ratings) else '', 'quote': quotes[i] if i < len(quotes) else '' } # 检查下一个是不是英文名 if title_index + 1 < len(titles) and titles[title_index + 1].startswith('/'): movie['en_title'] = titles[title_index + 1].replace('/ ', '') movies.append(movie) title_index += 1 with open('movies.json', 'w', encoding='utf-8') as f: json.dump(movies, f, ensure_ascii=False, indent=2) print('已保存到 movies.json')