新手必学:Python爬虫技巧大全,数据抓取与解析实战教程
本教程系统讲解Python爬虫入门方法,包括基础库安装、网页请求、HTML解析以及数据存储。通过实例代码和详细解析,帮助新手快速掌握网页抓取技能,实现自动化数据采集与处理。教程适用于2026最新Python版本,适合学习网页爬取、数据分析及小型爬虫项目实践。
正文教程
一、Python爬虫基础
爬虫是自动抓取网页数据的程序,Python提供丰富的库支持爬虫开发。
安装常用库:
pip install requests
pip install beautifulsoup4
技巧:
requests发送HTTP请求BeautifulSoup解析HTML内容
二、发送HTTP请求
使用requests获取网页内容。
示例代码:
import requests
url = "https://example.com"
response = requests.get(url)
if response.status_code == 200:
print(response.text[:500]) # 打印前500字符
技巧:
检查
status_code确保请求成功使用
headers伪装浏览器,避免反爬
三、HTML解析(BeautifulSoup)
解析网页内容,提取所需信息。
示例代码:
from bs4 import BeautifulSoup
html = response.text
soup = BeautifulSoup(html, "html.parser")
# 获取标题
title = soup.title.string
print("网页标题:", title)
# 获取所有链接
links = soup.find_all("a")
for link in links[:5]:
print(link.get("href"))
技巧:
soup.find查找第一个匹配元素soup.find_all查找所有匹配元素使用
.get("属性名")获取标签属性
四、数据存储
爬取的数据可存储为CSV或JSON。
保存为CSV:
import csv
data = [["姓名", "年龄"], ["Alice", 25], ["Bob", 30]]
with open("data.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)
保存为JSON:
import json
data = {"users": [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
技巧:
CSV适合表格型数据
JSON适合嵌套结构数据
五、实战示例:爬取示例网站标题
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.find_all("h2")
for t in titles[:10]:
print(t.text.strip())
效果:
打印网页前10个标题
可扩展为存入CSV或数据库
六、实用技巧
使用
headers模拟浏览器,避免反爬虫控制抓取频率,使用
time.sleep()防止封IP学会使用CSS选择器:
soup.select("div.class")先尝试小规模抓取,再扩展到批量爬取
遇到JavaScript渲染页面,可使用
selenium或Playwright
总结
Python爬虫是自动化数据采集的利器,掌握requests请求、BeautifulSoup解析与数据存储,可以快速实现网页抓取与信息提取。建议新手先学习基础HTTP请求和HTML解析,再逐步学习批量抓取、异常处理和反爬策略,从而全面提升爬虫开发能力。