包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取】
前言
在当今大数据时代,网络爬虫技术已成为获取互联网信息的重要手段。Python凭借其简洁的语法和丰富的第三方库,成为爬虫开发的首选语言。本文将介绍四个Python爬虫的实战案例,帮助读者掌握爬虫开发的核心技术。
案例一:静态网页数据抓取 - 豆瓣电影Top250
技术要点
requests库发送HTTP请求
BeautifulSoup解析HTML
基础反爬策略应对
import requests
from bs4 import BeautifulSoup
import csv
import time
def scrape_douban_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'
}
base_url = 'https://movie.douban.com/top250'
with open('douban_top250.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['排名', '电影名称', '评分', '评价人数', '经典台词'])
for start in range(0, 250, 25):
url = f"{base_url}?start={start}"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
for item in soup.find_all('div', class_='item'):
rank = item.find('em').text
title = item.find('span', class_='title').text
rating = item.find('span', class_='rating_num').text
num_reviews = item.find('div', class_='star').find_all('span')[-1].text[:-3]
quote = item.find('span', class_='inq').text if item.find('span', class_='inq') else ''
writer.writerow([rank, title, rating, num_reviews, quote])
time.sleep(2) # 礼貌性延迟
scrape_douban_top250()
关键点解析
使用随机User-Agent模拟浏览器访问
分页处理技巧
异常标签处理(如经典台词可能不存在)
设置访问间隔防止被封
案例二:动态内容抓取 - 京东商品信息
技术要点
Selenium模拟浏览器操作
等待机制处理动态加载
复杂页面元素定位
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
def scrape_jd_products(keyword):
driver = webdriver.Chrome()
driver.get('https://www.jd.com')
try:
# 搜索商品
search_box = driver.find_element(By.ID, 'key')
search_box.send_keys(keyword)
search_box.submit()
# 等待结果加载
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '.gl-item'))
)
# 滚动页面加载更多商品
for _ in range(3):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
# 提取商品信息
products = driver.find_elements(By.CSS_SELECTOR, '.gl-item')
for product in products[:10]: # 只取前10个商品
try:
name = product.find_element(By.CSS_SELECTOR, '.p-name em').text
price = product.find_element(By.CSS_SELECTOR, '.p-price strong').text
shop = product.find_element(By.CSS_SELECTOR, '.p-shop a').text
print(f"商品: {name}, 价格: {price}, 店铺: {shop}")
except:
continue
finally:
driver.quit()
scrape_jd_products('Python编程书籍')
关键点解析
Selenium模拟真实用户操作
显式等待确保元素加载完成
JavaScript滚动页面触发懒加载
异常处理保证程序稳定性
案例三:API接口数据抓取 - 微博热搜榜
技术要点
分析网站API接口
处理JSON数据
请求头参数设置
import requests
import json
def scrape_weibo_hot():
url = "https://weibo.com/ajax/side/hotSearch"
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",
"Referer": "https://weibo.com/",
"X-Requested-With": "XMLHttpRequest"
}
response = requests.get(url, headers=headers)
data = response.json()
hot_searches = []
for item in data['data']['realtime']:
hot_searches.append({
'rank': item['rank'],
'keyword': item['word'],
'hot': item['raw_hot'],
'tag': item.get('category', '无')
})
# 保存结果
with open('weibo_hot.json', 'w', encoding='utf-8') as f:
json.dump(hot_searches, f, ensure_ascii=False, indent=2)
return hot_searches
print(scrape_weibo_hot())
关键点解析
通过浏览器开发者工具分析API请求
必要的请求头设置
JSON数据解析与处理
数据存储为结构化格式
案例四:登录验证网站抓取 - 知乎内容采集
技术要点
模拟登录获取会话
Cookies持久化
复杂验证码处理
import requests
from bs4 import BeautifulSoup
class ZhihuSpider:
def __init__(self):
self.session = requests.Session()
self.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',
'Host': 'www.zhihu.com'
}
def login(self, username, password):
# 实际项目中需要处理验证码和更复杂的登录流程
login_url = 'https://www.zhihu.com/api/v3/oauth/sign_in'
data = {
'username': username,
'password': password,
'grant_type': 'password'
}
response = self.session.post(login_url, data=data, headers=self.headers)
return response.status_code == 200
def get_user_info(self, user_id):
url = f'https://www.zhihu.com/people/{user_id}'
response = self.session.get(url, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析用户信息
name = soup.find('h1', class_='ProfileHeader-name').text
headline = soup.find('div', class_='ProfileHeader-headline').text
followers = soup.find('div', class_='NumberBoard-followers').find('strong').text
return {
'name': name,
'headline': headline,
'followers': followers
}
def get_user_answers(self, user_id, limit=5):
url = f'https://www.zhihu.com/api/v4/members/{user_id}/answers'
params = {
'limit': limit,
'offset': 0,
'sort_by': 'created'
}
response = self.session.get(url, headers=self.headers, params=params)
answers = response.json()['data']
return [{
'title': answer['question']['title'],
'content': answer['content'],
'voteup_count': answer['voteup_count']
} for answer in answers]
# 使用示例
spider = ZhihuSpider()
if spider.login('your_username', 'your_password'):
user_info = spider.get_user_info('some_user_id')
print(user_info)
answers = spider.get_user_answers('some_user_id')
for answer in answers:
print(answer['title'])
关键点解析
Session对象保持登录状态
模拟复杂的登录流程
解析API返回的结构化数据
分页参数处理
结语
本文介绍了四种常见的Python爬虫实战案例,涵盖了静态网页抓取、动态内容获取、API接口调用和登录验证网站等典型场景。掌握这些技术后,读者可以根据实际需求进行组合和扩展,开发出功能更强大的爬虫程序。记住,爬虫技术是把双刃剑,务必在合法合规的前提下使用。
最后:
希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【点击这里领取!】
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习