可直接复制的Python爬虫源码:3个实战案例与实现解析
引言
Python是当前最流行的爬虫开发语言之一,其简洁的语法和丰富的第三方库使得爬虫开发变得高效且易于维护。本文将分享3个可直接复制使用的Python爬虫实战案例,涵盖不同类型的爬取需求,并详细解析其实现原理和关键技术点。
环境准备
在开始之前,请确保已安装以下Python库:
pip install requests beautifulsoup4 scrapy selenium案例一:基础静态页面爬虫 - 爬取豆瓣Top250电影
功能说明
爬取豆瓣电影Top250的电影名称、评分、导演和主演等信息。
实现源码
import requests
from bs4 import BeautifulSoup
def crawl_douban_top250():
url = 'https://movie.douban.com/top250'
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)
soup = BeautifulSoup(response.text, 'html.parser')
# 定位电影列表
movie_list = soup.find('ol', class_='grid_view').find_all('li')
for movie in movie_list:
# 提取电影信息
rank = movie.find('em').text
title = movie.find('span', class_='title').text
rating = movie.find('span', class_='rating_num').text
director_actor = movie.find('p', class_='').text.strip()
quote = movie.find('span', class_='inq')
quote = quote.text if quote else ''
print(f'排名: {rank}\n电影名: {title}\n评分: {rating}\n导演/主演: {director_actor}\n短评: {quote}\n{"-"*50}')
if __name__ == '__main__':
crawl_douban_top250()实现解析
- 请求发送:使用
requests库发送HTTP GET请求,设置User-Agent模拟浏览器访问,避免被网站反爬机制拦截。 - 页面解析:利用
BeautifulSoup库的html.parser解析器解析HTML响应,将字符串转换为可操作的DOM对象。 - 信息提取:
- 通过
find()和find_all()方法结合CSS类名定位DOM元素 - 提取电影排名、名称、评分等关键信息
- 处理可能为空的短评字段,避免程序报错
- 通过
案例二:动态页面爬虫 - 使用Selenium爬取AJAX加载内容
功能说明
爬取需要AJAX加载的动态内容,以某电商网站商品评论为例。
实现源码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
def crawl_dynamic_comments():
# 配置Chrome浏览器
chrome_options = Options()
chrome_options.add_argument('--headless') # 无头模式运行,不显示浏览器窗口
chrome_options.add_argument('--disable-gpu') # 禁用GPU加速
# 初始化浏览器驱动(需替换为你的chromedriver路径)
service = Service('/path/to/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
try:
# 访问目标页面
driver.get('https://example.com/product/comments')
# 等待页面加载完成
time.sleep(3)
# 点击"加载更多"按钮,获取更多评论
for i in range(3):
try:
load_more_btn = driver.find_element(By.XPATH, '//button[contains(text(), "加载更多")]')
load_more_btn.click()
time.sleep(2) # 等待AJAX请求完成
except Exception as e:
break # 没有更多评论时退出循环
# 提取所有评论
comments = driver.find_elements(By.CLASS_NAME, 'comment-item')
for idx, comment in enumerate(comments):
try:
username = comment.find_element(By.CLASS_NAME, 'username').text
content = comment.find_element(By.CLASS_NAME, 'comment-content').text
rating = comment.find_element(By.CLASS_NAME, 'rating').get_attribute('data-score')
print(f'评论 {idx+1}:\n用户: {username}\n评分: {rating}\n内容: {content}\n{"-"*50}')
except Exception as e:
continue # 跳过格式异常的评论
finally:
driver.quit() # 关闭浏览器,释放资源
if __name__ == '__main__':
crawl_dynamic_comments()实现解析
- 浏览器配置:使用Selenium的
Options配置Chrome浏览器,启用无头模式以提高效率。 - 驱动初始化:指定
chromedriver路径并初始化浏览器实例。 - 动态内容处理:
- 使用
time.sleep()等待页面和AJAX请求加载完成 - 模拟点击"加载更多"按钮获取完整评论列表
- 使用
find_element()和find_elements()定位并提取评论信息
- 使用
- 资源管理:在
finally块中关闭浏览器,确保资源得到释放
案例三:分布式爬虫 - 使用Scrapy框架
功能说明
使用Scrapy框架构建爬虫,适合大规模数据爬取需求。