6 回复
以前 PT 玩的多的时候也想过做一个类似的工具。
我来写一个爬取豆瓣电影Top250并在终端显示的小程序。这个程序会抓取电影排名、标题、评分和简介信息。
import requests
from bs4 import BeautifulSoup
import pandas as pd
from time import sleep
from random import random
def fetch_douban_movies():
"""爬取豆瓣电影Top250"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
movies = []
for page in range(0, 250, 25): # 总共10页,每页25部电影
url = f'https://movie.douban.com/top250?start={page}'
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
# 找到所有电影项
items = soup.find_all('div', class_='item')
for item in items:
# 提取排名
rank = item.find('em').text
# 提取标题
title_elem = item.find('span', class_='title')
title = title_elem.text if title_elem else '无标题'
# 提取评分
rating_elem = item.find('span', class_='rating_num')
rating = rating_elem.text if rating_elem else '无评分'
# 提取简介
quote_elem = item.find('span', class_='inq')
quote = quote_elem.text if quote_elem else '无简介'
movies.append({
'排名': rank,
'标题': title,
'评分': rating,
'简介': quote
})
print(f'已爬取第 {page//25 + 1} 页,共 {len(movies)} 部电影')
sleep(random() * 2 + 1) # 随机延迟,避免请求过快
except Exception as e:
print(f'爬取第 {page//25 + 1} 页时出错: {e}')
continue
return movies
def display_in_terminal(movies):
"""在终端中显示电影信息"""
print("\n" + "="*80)
print("豆瓣电影Top250".center(80))
print("="*80)
for movie in movies:
print(f"\n排名: {movie['排名']}")
print(f"标题: {movie['标题']}")
print(f"评分: {movie['评分']}")
print(f"简介: {movie['简介']}")
print("-"*60)
def main():
print("开始爬取豆瓣电影Top250...")
movies = fetch_douban_movies()
if movies:
print(f"\n爬取完成!共获取 {len(movies)} 部电影信息")
# 在终端显示
display_in_terminal(movies[:20]) # 只显示前20部,避免输出太长
# 保存到CSV文件(可选)
df = pd.DataFrame(movies)
df.to_csv('douban_top250.csv', index=False, encoding='utf-8-sig')
print(f"\n数据已保存到 douban_top250.csv")
else:
print("未能获取到电影数据")
if __name__ == '__main__':
main()
这个程序做了几件事:
- 使用requests库发送HTTP请求获取网页内容
- 用BeautifulSoup解析HTML,提取电影信息
- 添加了请求间隔避免被封
- 在终端用格式化的方式显示电影信息
- 可选保存到CSV文件
运行前需要安装依赖:
pip install requests beautifulsoup4 pandas
程序会先爬取所有250部电影,然后在终端显示前20部的详细信息。如果需要显示全部,可以把display_in_terminal(movies[:20])改成display_in_terminal(movies)。
注意:豆瓣有反爬机制,如果频繁请求可能会被限制。这个程序已经加了随机延迟,但大量爬取时还是要适度。
总结:用requests+BeautifulSoup组合就能搞定基础爬虫。
赞一个!👍
挺简单的,写着玩
cmd 里中文乱码
cmd 默认窗口编码的缘故,执行 chcp 65001 之后就能显示中文了~

