52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
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'<span class="title">([^<&]+)</span>'
|
|
rating_pattern = r'<span class="rating_num"[^>]*>(\d+\.?\d*)</span>'
|
|
quote_pattern = r'<span class="inq">([^<]+)</span>'
|
|
|
|
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')
|
|
|
|
with open('movies.json', 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
print(f'共保存 {len(data)} 部电影')
|
|
for m in data[:3]:
|
|
print(f" {m['rank']}. {m['title']} ({m['en_title']}) - {m['rating']}") |