完成作业6
This commit is contained in:
54
2026.3.31..05.py
Normal file
54
2026.3.31..05.py
Normal file
@@ -0,0 +1,54 @@
|
||||
|
||||
import re
|
||||
import csv
|
||||
|
||||
|
||||
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
|
||||
|
||||
pattern = r'<span class="title">([^<&]+)</span>'
|
||||
titles = re.findall(pattern, html)
|
||||
|
||||
chinese_titles = [t for t in titles if not t.startswith('/')]
|
||||
|
||||
top10 = chinese_titles[:10]
|
||||
|
||||
rating_pattern = r'<span class="rating_num"[^>]*>(\d+\.?\d*)</span>'
|
||||
|
||||
ratings = re.findall(rating_pattern, html)
|
||||
|
||||
movies = []
|
||||
for i in range(min(10, len(titles))):
|
||||
title = titles[i] if not titles[i].startswith('/') else ''
|
||||
en_title = titles[i+1] if i+1 < len(titles) and titles[i+1].startswith('/') else ''
|
||||
en_title = en_title.replace('/ ', '') if en_title else ''
|
||||
|
||||
movie = {
|
||||
'rank': i + 1,
|
||||
'title': title,
|
||||
'en_title': en_title,
|
||||
'rating': ratings[i] if i < len(ratings) else ''
|
||||
}
|
||||
movies.append(movie)
|
||||
|
||||
with open('movies.csv', 'w', encoding='utf-8', newline='') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=['rank', 'title', 'en_title', 'rating'])
|
||||
writer.writeheader()
|
||||
writer.writerows(movies)
|
||||
|
||||
print('已保存到 movies.csv')
|
||||
|
||||
with open('movies.csv', 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
print(line.strip())
|
||||
|
||||
chinese_titles = [t for t in titles if not t.startswith('/')]
|
||||
|
||||
print('电影名称(前10部):')
|
||||
for i, title in enumerate(chinese_titles[:10], 1):
|
||||
print(f'{i}. {title}')
|
||||
Reference in New Issue
Block a user