Python爬虫实战:利用Requests和BeautifulSoup库轻松爬取豆瓣电影TOP250排行榜
引言
随着互联网的飞速发展,网络爬虫已经成为了一个非常重要的工具,用于从网页中自动提取信息。Python 作为一种非常适合进行网络爬虫开发的语言,拥有众多强大的库来简化这一过程。本篇文章将带你深入了解如何使用 requests 和 BeautifulSoup 来爬取豆瓣电影 TOP250 页面的信息,并介绍一些实用的反爬虫规避技巧。
准备工作
在开始之前,请确保你的 Python 环境已经安装了必要的库:
pip install requests beautifulsoup4 lxml pandas openpyxl
我们将会使用的库包括:
requests: 发送 HTTP 请求。BeautifulSoup: 解析 HTML 文档。lxml: BeautifulSoup 的解析器之一,提供更快的解析速度。pandas: 数据分析和操作的强大工具。openpyxl: Excel 文件读写的库。第一部分:分析目标网站
网站结构分析
打开豆瓣电影 TOP250 页面 (https://movie.douban.com/top250) 25 部电影。页面底部提供了分页导航链接,点击这些链接可以浏览不同的页面。通过浏览器的开发者工具,我们可以查看网页的源代码,找到所需信息对应的 HTML 标签。
分析步骤
- 确定目标: 我们希望获取每部电影的标题、评分、评价人数以及一句话简介。
- 查找模式: 在 HTML 源码中寻找包含上述信息的标签及其属性。例如,电影标题可能位于
<span class="title">中,评分则可能位于<span class="rating_num">中。
第二部分:编写爬虫代码
发送请求并获取响应
首先,我们需要发送 HTTP 请求到目标 URL 并获取其内容。这里我们使用 requests 库来完成这项任务。
import requests
def fetch_page(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
else:
print(f"Failed to retrieve page: {url}")
return None
// 注释:定义一个函数来发送请求,并检查响应状态是否成功。
解析 HTML 并提取信息
获取到网页内容后,接下来的任务是解析 HTML 并从中提取有用的数据。我们将使用 BeautifulSoup 来实现这一点。
from bs4 import BeautifulSoup
def parse_movies(html_content):
soup = BeautifulSoup(html_content, 'lxml')
movies = []
for item in soup.find_all('div', class_='item'):
title = item.find('span', class_='title').text
rating = item.find('span', class_='rating_num').text
review_count = item.find('div', class_='star').contents[3].text.strip('人评价')
quote_tag = item.find('span', class_='inq')
quote = quote_tag.text if quote_tag else ''
movie_info = {'title': title, 'rating': rating, 'review_count': review_count, 'quote': quote}
movies.append(movie_info)
return movies
// 注释:该函数接收HTML内容作为输入,解析出电影列表,返回一个包含电影信息的列表。
处理分页
由于 TOP250 页面分为多个子页面,我们需要遍历所有页面以收集完整的信息。
base_url = "https://movie.douban.com/top250?start={}"
all_movies = []
for i in range(0, 250, 25):
url = base_url.format(i)
html_content = fetch_page(url)
if html_content:
all_movies.extend(parse_movies(html_content))
time.sleep(1) # 添加延迟避免触发反爬机制
// 注释:循环遍历所有页面,添加延迟防止触发反爬虫机制。
第三部分:处理反爬虫措施
延迟请求
为了避免过于频繁地访问服务器,我们可以在每次请求之间加入短暂的延迟。
import time
time.sleep(1) # 每次请求前暂停一秒
使用代理 IP
如果同一个 IP 地址短时间内发出大量请求,可能会导致 IP 被封禁。使用代理 IP 可以有效缓解这一问题。
proxies = {
'http': 'http://your_proxy_ip:port',
'https': 'https://your_proxy_ip:port',
}
response = requests.get(url, headers=headers, proxies=proxies)
错误处理与重试机制
在网络请求过程中,难免会遇到各种异常情况。因此,建立健壮的错误处理和重试机制是非常必要的。
import logging
logging.basicConfig(level=logging.INFO)
max_retries = 3
retry_delay = 5 # 重试间隔时间(秒)
def safe_fetch_page(url, retries=max_retries):
attempt = 0
while attempt < retries:
try:
return fetch_page(url)
except Exception as e:
logging.error(f"Error fetching {url}: {e}")
attempt += 1
if attempt < retries:
logging.info(f"Retrying ({attempt}/{retries})...")
time.sleep(retry_delay)
logging.error(f"Failed to fetch {url} after {retries} attempts.")
return None
第四部分:数据存储与导出
存储为 CSV 或 Excel 文件
获取到的数据通常需要保存下来以便后续分析或分享。这里我们将演示如何使用 pandas 将数据导出为 CSV 或 Excel 文件。
import pandas as pd
df = pd.DataFrame(all_movies)
df.to_csv('douban_top250.csv', index=False, encoding='utf-8-sig') # 导出为CSV文件
df.to_excel('douban_top250.xlsx', index=False) # 导出为Excel文件
数据可视化
有了数据之后,还可以进一步进行数据分析和可视化。例如,我们可以绘制电影评分分布图等。
import matplotlib.pyplot as plt
ratings = df['rating'].astype(float)
plt.hist(ratings, bins=10)
plt.title('Movie Ratings Distribution')
plt.xlabel('Rating')
plt.ylabel('Count')
plt.show()
结论
通过本文的学习,你应当能够掌握使用 Python 的 requests 和 BeautifulSoup 库来爬取豆瓣电影 TOP250 页面的基本技能,并了解到如何应对常见的反爬虫策略。同时,我们也介绍了如何对爬取的数据进行存储和简单的可视化分析。记住,在实际应用中要始终遵守法律法规和服务条款,合理合法地利用爬虫技术。

作者:yansideyucsdn