文章目录
一、环境准备(5分钟搞定)
安装Python环境咱们直接用Anaconda全家桶(省心!),打开终端输入:
pip install requests beautifulsoup4
这俩库堪称爬虫界的"黄金搭档"(requests负责网络请求,BeautifulSoup解析网页结构)
二、第一个爬虫实例(震惊!10行代码就能抓数据)
以抓取豆瓣电影Top250为例:
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
movies = soup.find_all('div', class_='hd')
for movie in movies[:5]: # 只取前5条
title = movie.a.span.text
print(f"《{title}》")
运行结果你会看到:
《肖申克的救赎》
《霸王别姬》
《阿甘正传》
《泰坦尼克号》
《这个杀手不太冷》
三、数据解析核心技巧(CSS选择器实战)
BeautifulSoup的三大绝招:
- find():找单个元素
first_movie = soup.find('div', class_='hd')
- find_all():抓取同类元素
all_ratings = soup.find_all('span', class_='rating_num')
- select()(强烈推荐!):
# 获取所有电影标题
titles = soup.select('div.hd > a > span:nth-child(1)')
(超级重要)CSS选择器速记口诀:
>
表示直接子元素.class
选择类名#id
选择ID[attribute=value]
属性选择器
四、数据存储实战(两种常用方式)
方案1:保存到txt文件
with open('movies.txt', 'w', encoding='utf-8') as f:
for title in titles:
f.write(title.text + '\n')
方案2:保存到CSV(更适合表格数据)
import csv
with open('movies.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['序号', '电影名称', '评分'])
for index, (title, rating) in enumerate(zip(titles, ratings)):
writer.writerow([index+1, title.text, rating.text])
五、反爬虫应对技巧(新人必看)
- 设置请求头(伪装浏览器):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...'
}
response = requests.get(url, headers=headers)
- 添加延迟(避免被封IP):
import time
time.sleep(3) # 每次请求间隔3秒
- 使用代理IP(进阶玩法):
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080'
}
requests.get(url, proxies=proxies)
六、常见坑点预警(血泪经验总结)
- 遇到403错误:说明被网站识别为爬虫 → 检查请求头是否设置
- 数据抓取为空:网页结构可能有变化 → 用开发者工具重新分析页面
- 突然无法连接:可能IP被封 → 切换网络/使用代理
- 中文乱码问题:记得设置正确的编码 →
response.encoding = 'utf-8'
七、法律与道德边界(必读!)
- ✅ 允许爬取:公开数据、不涉及个人隐私
- ❌ 禁止爬取:需登录才能查看的数据、商业机密
- (重要)必须遵守:目标网站的
robots.txt
协议
八、下一步学习路径
想进阶的童鞋可以研究:
- Scrapy框架(企业级爬虫解决方案)
- Selenium模拟浏览器(对付JavaScript渲染的页面)
- 分布式爬虫(提升抓取效率)
- 验证码破解(慎用!建议优先考虑合法合规方式)
小贴士:新手建议从静态网页开始练手,推荐练习网站:豆瓣电影、维基百科、政府公开数据平台等
结语
爬虫就像互联网世界的"数据矿工",但记住:技术是把双刃剑!咱们既要享受数据抓取的乐趣,更要遵守网络世界的游戏规则。现在打开你的Python编辑器,开启你的第一个爬虫项目吧!(记得先从简单的网站练手哦~)