上传文件至 /
This commit is contained in:
43
26.03.31 43movies.py
Normal file
43
26.03.31 43movies.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import requests
|
||||
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
|
||||
|
||||
title_pattern = r'<span class="title">([^<&]+)</span>'
|
||||
rating_pattern = r'<span class="rating_num"[^>]*>(\d+\.?\d*)</span>'
|
||||
|
||||
titles = re.findall(title_pattern, html)
|
||||
ratings = re.findall(rating_pattern, html)
|
||||
|
||||
movies = []
|
||||
for i in range(min(10, len(titles))):
|
||||
# 每两个title为一组(中文 + 可能有的英文)
|
||||
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())
|
||||
Reference in New Issue
Block a user