Python爬虫之使用方法|系统入门与实战指南

一、网络爬虫的本质与法律边界

Python爬虫之使用方法的核心在于模拟浏览器行为,自动获取网络资源。但所有技术应用都需在法律框架内进行。根据《网络安全法》《数据安全法》等法规,爬取公开信息用于个人学习、科研等非商业用途通常被允许,但严禁窃取商业秘密、绕过技术防护措施或大规模采集用户隐私数据。

例如,2022年某科技公司因爬取某社交平台用户公开评论并用于商业分析,被法院认定构成不正当竞争,赔偿经济损失120万元。因此,在实施Python爬虫之使用方法前,务必遵循“robots.txt”协议、控制请求频率、避免对目标服务器造成压力。

⚠️ 法律合规提醒
  • 禁止爬取明确标注“禁止爬取”的资源
  • 不得突破验证码、IP限制等防护机制
  • 禁止采集涉及个人身份、健康、行踪等敏感信息
  • 商业使用需获得数据提供方明确授权

在合法合规前提下,Python爬虫之使用方法已成为数据采集、舆情监测、市场调研等领域的基础工具。掌握其原理与规范,是开发者必备的技能素养。

二、爬虫技术栈全景图

完整的Python爬虫之使用方法技术栈包含四个核心环节:

环节 核心任务 常用工具/库 典型应用场景
请求发送 模拟HTTP请求获取页面数据 requests、aiohttp 静态页面数据采集
内容解析 从HTML/XML中提取目标信息 BeautifulSoup、lxml、XPath 商品价格、新闻标题提取
动态处理 应对JavaScript动态渲染内容 Selenium、Playwright 电商商品详情页、实时股票数据
数据存储 结构化保存采集结果 CSV、JSON、MySQL、MongoDB 数据持久化、后续分析处理

下文将围绕Python爬虫之使用方法的完整流程,逐层解析各环节的关键技术点与最佳实践。

三、爬虫工作流程详解

Python爬虫之使用方法的标准工作流程可分解为以下五个阶段:

① 目标分析

明确采集目标、数据字段、更新频率及反爬特征。例如采集某招聘网站岗位信息时,需确认字段包括:岗位名称、薪资范围、工作地点、学历要求、经验要求等。

② 请求构造

根据目标网站结构,构建合理请求。以GET请求为例,需设置User-Agent、Accept-Language等标准请求头,避免被识别为异常访问。

③ 数据获取

发送请求并接收响应。使用requests库时,建议添加超时参数(timeout=5)防止程序卡死,并捕获ConnectionError、Timeout等异常。

④ 内容解析

采用XPath或CSS选择器精准定位目标元素。例如使用lxml提取所有商品名称:tree.xpath('//div[@class="product-name"]/text()')

⑤ 数据存储

将结构化数据保存至数据库或文件。使用pandas可快速导出CSV:df.to_csv('products.csv', index=False, encoding='utf-8-sig')

掌握该流程是实施Python爬虫之使用方法的基础,后续章节将针对各环节展开详细说明。

核心库详解与实战应用

一、requests库:HTTP请求的基石

Python爬虫之使用方法中,requests库是发起HTTP请求的首选工具。其简洁的API设计大幅降低了网络请求的复杂度。以下为典型使用场景:

import requests # 基础GET请求 url = "https://www.example.com/api/data" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } response = requests.get(url, headers=headers, timeout=5) response.raise_for_status() # 检查HTTP错误 data = response.json()

在采集分页数据时,可通过参数动态构建URL:

# 分页参数构造 base_url = "https://api.example.com/search" for page in range(1, 6): # 采集前5页 params = {"keyword": "Python", "page": page} response = requests.get(base_url, params=params, headers=headers) # 处理响应数据...

对于POST请求(如模拟表单提交),需指定data或json参数:

# POST请求示例 login_url = "https://www.example.com/login" payload = { "username": "user123", "password": "pass456" } response = requests.post(login_url, data=payload, headers=headers)

注意:requests库默认不处理JavaScript渲染内容,需结合Selenium等工具实现动态页面抓取。

二、BeautifulSoup:HTML解析利器

BeautifulSoup是Python中最流行的HTML/XML解析库,配合lxml解析器可实现高效解析。典型用法如下:

from bs4 import BeautifulSoup import requests # 获取页面内容 url = "https://www.example.com/news" response = requests.get(url) html = response.text # 解析HTML soup = BeautifulSoup(html, "lxml") # 提取标题 titles = [tag.get_text() for tag in soup.select("h2.article-title")] print(f"共找到 {len(titles)} 篇文章标题") # 提取链接与文本 for link in soup.select("a"): href = link.get("href") text = link.get_text(strip=True) if href and text: print(f"[{text}] → {href}")

当面对复杂结构时,可使用CSS选择器精准定位元素:

# 提取特定区域的列表项 items = soup.select("#product-list li.product-item") for item in items: name = item.select_one(".name").get_text() price = item.select_one(".price").get_text() print(f"{name}:{price}")

注意:BeautifulSoup解析速度受HTML规模影响较大,对于超大文件建议使用lxml直接解析。

三、XPath:结构化数据提取

XPath是XML路径语言,适用于复杂HTML结构的数据提取。其优势在于支持条件筛选、轴操作等高级功能。典型示例:

from lxml import etree import requests url = "https://www.example.com/products" response = requests.get(url) tree = etree.HTML(response.text) # 提取所有商品名称 names = tree.xpath('//div[@class="product-card"]//span[@class="name"]/text()') # 提取价格区间(含条件判断) prices = tree.xpath('//span[@class="price"][contains(text(), "¥")]') # 提取链接及文本(多层嵌套) links = tree.xpath('//a[contains(@href, "/detail")]/@href') texts = tree.xpath('//a[contains(@href, "/detail")]/text()')

常见XPath表达式示例:

表达式 说明 应用场景
//a[@class='next']/@href 获取下一页链接 分页爬取
//ul[@id='menu']/li[1]/a/text() 提取菜单第一项文本 导航栏数据采集
//div[contains(@class, 'price')] 模糊匹配class名 动态class名处理
//img/@src[starts-with(., 'https://')] 筛选有效图片链接 图片资源采集

掌握XPath是实现Python爬虫之使用方法高精度数据提取的关键技能。

四、Selenium:动态页面解决方案

针对JavaScript渲染的页面,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 # 初始化浏览器驱动 options = webdriver.ChromeOptions() options.add_argument("--headless") # 无头模式 options.add_argument("--disable-gpu") driver = webdriver.Chrome(options=options) try: driver.get("https://www.example.com/dynamic-page") # 等待元素加载完成 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, ".dynamic-content")) ) # 获取渲染后的内容 html = driver.page_source # 进一步解析... finally: driver.quit()

常见动态加载场景解决方案:

问题类型 解决方案 示例
懒加载图片 滚动页面触发加载 driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
AJAX分页 监听XHR请求 使用selenium-wire捕获网络请求
动态验证码 跳过或人工介入 调用第三方识别API或人工输入

注意:Selenium资源占用较高,仅在必要时使用。对于简单动态内容,可优先尝试分析XHR接口直接请求。

反爬机制应对策略

User-Agent识别
请求频率限制
验证码防御
IP封禁策略

一、User-Agent识别与伪装

多数网站通过User-Agent字段判断请求来源。常见反爬策略包括:

  • 拒绝非浏览器User-Agent(如python-requests)
  • 检测User-Agent真实性(如包含不存在的浏览器版本)
  • 动态更新UA白名单

Python爬虫之使用方法中有效的UA伪装方案:

from fake_useragent import UserAgent # 动态生成真实UA ua = UserAgent() headers = { "User-Agent": ua.random, "Accept-Language": "zh-CN,zh;q=0.9", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" }

更高级的方案是使用浏览器指纹模拟:

# 浏览器指纹关键参数 fingerprint = { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "platform": "Win32", "language": "zh-CN", "hardwareConcurrency": 8, "deviceMemory": 8 }

注意:UA伪装需配合其他策略使用,单一措施易被绕过。

二、请求频率限制应对

网站通常通过单位时间请求数(RPM)限制访问频率。典型处理方式:

  • 添加随机延迟(避免固定间隔)
  • 使用请求队列控制并发
  • 检测429状态码(Too Many Requests)
import time import random # 带随机延迟的请求 def safe_request(url, headers, retries=3): for i in range(retries): try: time.sleep(random.uniform(0.5, 2.0)) # 0.5-2秒随机延迟 response = requests.get(url, headers=headers, timeout=5) if response.status_code == 429: wait_time = int(response.headers.get("Retry-After", 60)) print(f"触发限流,等待{wait_time}秒") time.sleep(wait_time) continue response.raise_for_status() return response except requests.exceptions.RequestException as e: print(f"请求失败 ({i+1}/{retries}): {e}") if i == retries - 1: raise time.sleep(2) return None

更专业的方案是集成Scrapy框架的下载延迟控制:

# settings.py配置 DOWNLOAD_DELAY = 1.5 # 平均延迟1.5秒 RANDOMIZE_DOWNLOAD_DELAY = True # 启用随机延迟 CONCURRENT_REQUESTS = 16 # 最大并发数

三、验证码识别方案

常见验证码类型及应对策略:

验证码类型 识别难度 解决方案 适用场景
滑动拼图 中 OpenCV轨迹模拟 电商登录页
点选验证 高 第三方识别API 金融网站
图形验证码 低 Tesseract OCR 老系统登录页
行为验证 极高 跳过或人工介入 高安全要求网站

使用Tesseract识别基础验证码示例:

from PIL import Image import pytesseract # 图片预处理 image = Image.open("captcha.png") image = image.convert("L") # 转灰度 image = image.point(lambda x: 0 if x < 128 else 255) # 二值化 # OCR识别 text = pytesseract.image_to_string(image, config="--psm 7") print(f"识别结果: {text}")

注意:复杂验证码识别准确率有限,建议结合人工验证流程。

四、IP封禁与代理池管理

IP封禁是网站最有效的反爬手段之一。应对方案包括:

  • 构建高质量代理池
  • 实现IP健康度检测
  • 动态轮换机制
import random import requests # 代理池管理 PROXIES = [ "http://123.123.123.1:8080", "http://111.222.333.4:8080", "http://555.666.777.8:8080" ] def get_random_proxy(): return random.choice(PROXIES) def request_with_proxy(url, headers): for _ in range(3): # 最多重试3次 try: proxy = get_random_proxy() proxies = {"http": proxy, "https": proxy} response = requests.get(url, headers=headers, proxies=proxies, timeout=5) if response.status_code == 200: return response except: continue return None

更完善的方案是集成Scrapy-Redis分布式爬虫,自动管理代理池与请求调度:

# settings.py配置 DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 1, 'myproject.middlewares.ProxyMiddleware': 101, }

注意:免费代理稳定性差,建议使用付费代理服务(如快代理、芝麻HTTP)。

模拟登录技术方案

一、表单登录全流程解析

模拟登录需完成以下关键步骤:

① 获取登录页

获取登录页HTML,提取隐藏字段(如CSRF Token)

② 构造登录参数

填充用户名、密码、Token等字段,加密处理敏感信息

③ 发送POST请求

携带Cookie发送登录请求,处理响应结果

④ 验证登录状态

检查响应URL、Cookie或访问个人主页确认登录成功

完整示例代码:

import requests from bs4 import BeautifulSoup # 初始化会话 session = requests.Session() # 1. 获取登录页 login_url = "https://example.com/login" resp = session.get(login_url) soup = BeautifulSoup(resp.text, "lxml") # 2. 提取CSRF Token token = soup.find("input", {"name": "csrf_token"})["value"] # 3. 构造登录参数 payload = { "username": "user123", "password": "pass456", "csrf_token": token, "remember_me": "on" } # 4. 发送登录请求 login_action = soup.find("form")["action"] full_login_url = resp.url.replace("/login", login_action) session.post(full_login_url, data=payload) # 5. 验证登录状态 profile_resp = session.get("https://example.com/profile") if "退出登录" in profile_resp.text: print("登录成功!")

注意:现代网站常采用加密密码传输,需分析JS源码提取加密逻辑。

二、OAuth授权登录方案

对于支持OAuth 2.0的网站,可使用授权码流程获取访问令牌:

# OAuth 2.0授权流程 import requests from urllib.parse import urlencode # 1. 重定向到授权页 client_id = "your_client_id" redirect_uri = "https://your-app.com/callback" scopes = "user_profile,email" auth_url = f"https://example.com/oauth/authorize?{urlencode({ "client_id": client_id, "redirect_uri": redirect_uri, "response_type": "code", "scope": scopes })}" # 用户访问该URL并授权后,重定向到redirect_uri?code=AUTH_CODE # 2. 用授权码换取访问令牌 token_url = "https://example.com/oauth/token" data = { "client_id": client_id, "client_secret": "your_client_secret", "code": "AUTH_CODE_FROM_REDIRECT", "grant_type": "authorization_code", "redirect_uri": redirect_uri } token_resp = requests.post(token_url, data=data) access_token = token_resp.json()["access_token"] # 3. 使用令牌访问API headers = {"Authorization": f"Bearer {access_token}"} profile_resp = requests.get("https://api.example.com/user/profile", headers=headers)

OAuth方案更安全可靠,推荐优先使用。注意:需在开发者平台注册应用并配置回调地址。

三、Cookie持久化管理

登录后需保存Cookie以维持会话状态。推荐方案:

import pickle import requests # 保存Cookie session = requests.Session() # ... 登录操作 ... with open("cookies.pkl", "wb") as f: pickle.dump(session.cookies, f) # 加载Cookie session = requests.Session() with open("cookies.pkl", "rb") as f: session.cookies.update(pickle.load(f))

Scrapy框架提供更便捷的Cookie管理:

# settings.py COOKIES_ENABLED = True COOKIES_DEBUG = True # 调试时查看Cookie变化 # spider.py def start_requests(self): yield scrapy.Request( url="https://example.com/profile", cookies={"session_id": "abc123", "user_token": "xyz789"} )

注意:Cookie有有效期,需定期刷新。可结合Redis存储实现分布式会话管理。

数据存储方案对比

CSV与JSON存储
关系型数据库
NoSQL数据库
Elasticsearch集成

一、CSV与JSON格式存储

适用于小规模数据或临时存储场景:

import csv import json # CSV存储 data = [ {"name": "Python入门", "price": "¥59", "sales": "1200"}, {"name": "进阶实战", "price": "¥129", "sales": "850"} ] with open("products.csv", "w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=["name", "price", "sales"]) writer.writeheader() writer.writerows(data) # JSON存储 with open("products.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)

优势:简单直观,无需额外依赖;劣势:不支持复杂查询,数据量大时性能差。

二、关系型数据库(MySQL)

适合结构化数据存储,支持事务与复杂查询:

import pymysql # 创建连接 conn = pymysql.connect( host="localhost", user="root", password="password", database="crawler_db", charset="utf8mb4" ) cursor = conn.cursor() # 创建表 cursor.execute(""" CREATE TABLE IF NOT EXISTS products ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL, price DECIMAL(10,2), sales INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # 插入数据 sql = "INSERT INTO products (name, price, sales) VALUES (%s, %s, %s)" cursor.executemany(sql, [ ("Python入门", 59.00, 1200), ("进阶实战", 129.00, 850) ]) conn.commit() cursor.close() conn.close()

使用ORM框架(如SQLAlchemy)可进一步简化操作:

from sqlalchemy import create_engine, Column, Integer, String, DECIMAL from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Product(Base): __tablename__ = "products" id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) price = Column(DECIMAL(10,2)) sales = Column(Integer) # 创建表 engine = create_engine("mysql+pymysql://root:password@localhost/crawler_db") Base.metadata.create_all(engine) # 插入数据 Session = sessionmaker(bind=engine) session = Session() session.add_all([ Product(name="Python入门", price=59.00, sales=1200), Product(name="进阶实战", price=129.00, sales=850) ]) session.commit() session.close()

三、NoSQL数据库(MongoDB)

适合非结构化数据存储,高扩展性:

from pymongo import MongoClient # 连接数据库 client = MongoClient("mongodb://localhost:27017/") db = client["crawler_db"] collection = db["products"] # 插入数据 products = [ {"name": "Python入门", "price": 59.00, "sales": 1200, "tags": ["基础", "入门"]}, {"name": "进阶实战", "price": 129.00, "sales": 850, "tags": ["实战", "进阶"]} ] collection.insert_many(products) # 查询数据 for doc in collection.find({"price": {"$gt": 50}}): print(doc)

优势:灵活的文档结构,支持嵌套数据;劣势:不支持事务(4.0后部分支持),复杂查询效率较低。

四、Elasticsearch全文检索集成

适用于需要搜索功能的场景:

from elasticsearch import Elasticsearch # 初始化客户端 es = Elasticsearch([{"host": "localhost", "port": 9200}]) # 创建索引 es.indices.create(index="products", ignore=400) # 插入数据 doc = { "name": "Python爬虫实战", "price": 159.00, "sales": 680, "description": "系统讲解爬虫技术" } es.index(index="products", id=1, document=doc) # 搜索 result = es.search( index="products", body={"query": {"match": {"name": "爬虫"}}} ) for hit in result["hits"]["hits"]: print(hit["_source"])

优势:强大的全文检索能力;劣势:资源占用高,部署复杂。

实战项目拆解

一、招聘网站岗位数据采集

Python爬虫之使用方法实战案例:采集某招聘网站Python相关岗位信息

import requests from bs4 import BeautifulSoup import time import random def crawl_jobs(keyword="Python", pages=3): base_url = "https://www.zhipin.com/job_detail/" jobs = [] for page in range(1, pages + 1): url = f"{base_url}?query={keyword}&page={page}" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } try: response = requests.get(url, headers=headers, timeout=5) soup = BeautifulSoup(response.text, "lxml") # 提取岗位列表 job_cards = soup.select(".job-card-box") for card in job_cards: title = card.select_one(".job-title").get_text() salary = card.select_one(".salary").get_text() city = card.select_one(".job-area").get_text() experience = card.select_one(".job-limit").find_all("span")[0].get_text() education = card.select_one(".job-limit").find_all("span")[1].get_text() jobs.append({ "title": title, "salary": salary, "city": city, "experience": experience, "education": education }) print(f"第{page}页采集完成,共{len(job_cards)}条") time.sleep(random.uniform(1, 2)) # 随机延迟 except Exception as e: print(f"页码{page}采集失败: {e}") return jobs # 执行采集 jobs = crawl_jobs(keyword="Python", pages=2) print(f"总采集岗位数: {len(jobs)}")

采集结果示例:

[ {"title": "Python开发工程师", "salary": "15K-25K", "city": "北京", "experience": "3-5年", "education": "本科"}, {"title": "爬虫工程师", "salary": "20K-35K", "city": "上海", "experience": "5-10年", "education": "硕士"}, {"title": "Python数据分析师", "salary": "12K-20K", "city": "深圳", "experience": "1-3年", "education": "本科"} ]

后续可将数据存入数据库进行可视化分析,如薪资分布、城市需求热力图等。

二、电商价格监控系统

构建实时价格监控系统,追踪商品价格波动:

import schedule import time from datetime import datetime def monitor_price(product_id): """监控单个商品价格""" url = f"https://api.example.com/product/{product_id}" headers = {"User-Agent": "Mozilla/5.0"} try: response = requests.get(url, headers=headers) data = response.json() current_price = data["price"] last_price = get_last_price(product_id) # 从数据库获取历史价格 if current_price != last_price: save_price_record(product_id, current_price) send_alert(product_id, last_price, current_price) except Exception as e: log_error(f"监控失败: {e}") def send_alert(product_id, old_price, new_price): """发送价格变动通知""" change = "上涨" if new_price > old_price else "下降" message = f"商品{product_id}价格{change}:{old_price} → {new_price}" print(f"[{datetime.now()}] {message}") # 定时任务:每2小时检查一次 schedule.every(2).hours.do(lambda: monitor_price("PROD12345")) # 启动监控 while True: schedule.run_pending() time.sleep(60)

关键优化点:

  • 使用Redis缓存减少API调用频率
  • 设置价格变动阈值(如±5%才触发告警)
  • 集成邮件/企业微信通知
  • 构建价格趋势可视化图表

三、舆情监测系统

基于关键词采集社交媒体内容,实现舆情预警:

import tweepy import re def monitor_social_media(keywords): """监控社交媒体舆情""" # Twitter API认证 client = tweepy.Client(bearer_token="YOUR_BEARER_TOKEN") for keyword in keywords: # 搜索相关推文 tweets = client.search_recent_tweets( query=f"{keyword} lang:zh", max_results=10, tweet_fields=["created_at", "public_metrics"] ) for tweet in tweets.data: # 文本预处理 text = re.sub(r"http\S+", "", tweet.text) # 去除链接 text = re.sub(r"#\S+", "", text) # 去除话题 # 情感分析 sentiment = analyze_sentiment(text) if sentiment == "negative": alert舆情(keyword, text, sentiment) def analyze_sentiment(text): """简单情感分析(实际应用需调用AI API)""" positive_words = ["好", "棒", "推荐", "满意"] negative_words = ["差", "垃圾", "失望", "投诉"] score = sum(1 for w in positive_words if w in text) - sum(1 for w in negative_words if w in text) if score > 0: return "positive" elif score < 0: return "negative" else: return "neutral"

系统可集成到企业微信,实时推送负面舆情预警,辅助决策。

辅助工具与开发环境

一、开发工具推荐

工具类型 推荐方案 优势 适用场景
IDE PyCharm / VS Code 智能提示、调试支持 日常开发
调试代理 Fiddler / Charles 抓包分析请求 逆向分析
XPath测试 Chrome插件XPath Helper 实时验证表达式 解析调试
数据可视化 Tableau / Matplotlib 图表生成 结果展示

二、开发环境配置

Python爬虫之使用方法环境搭建步骤:

  • 安装Python 3.8+(推荐使用pyenv管理多版本)
  • 创建虚拟环境:python -m venv venv && source venv/bin/activate
  • 安装基础库:pip install requests beautifulsoup4 lxml
  • 安装Selenium:pip install selenium + 下载对应浏览器驱动
  • 配置代理池(可选):pip install redis scrapy
  • 项目结构建议:

    my_spider/ ├── config/ │ ├── settings.py # 配置文件 │ └── proxies.txt # 代理列表 ├── spiders/ │ ├── base_spider.py # 基础类 │ └── zhipin_spider.py # 具体爬虫 ├── pipelines/ │ ├── db_pipeline.py # 数据库存储 │ └── es_pipeline.py # ES存储 ├── utils/ │ ├── logger.py # 日志工具 │ └── captcha.py # 验证码处理 ├── main.py # 入口文件 └── requirements.txt # 依赖列表

    安全与合规实践

    一、反反爬策略综合指南

    实施Python爬虫之使用方法时需遵循以下安全原则:

    风险类型 防范措施 合规建议
    服务器压力 控制并发数(≤5)、设置延迟 访问频率≤1次/秒
    数据滥用 仅采集必要字段 避免采集个人敏感信息
    法律风险 遵守robots.txt 商业使用需授权
    账号封禁 模拟真实用户行为 禁用自动化脚本

    二、数据安全处理

    Python爬虫之使用方法中需注意:

    • 加密存储敏感数据(如API密钥)
    • 使用HTTPS协议传输数据
    • 定期清理临时文件
    • 添加数据访问日志审计
    import os from cryptography.fernet import Fernet # 生成密钥(首次运行时保存到安全位置) key = Fernet.generate_key() cipher = Fernet(key) # 加密存储 with open("config.txt", "rb") as f: encrypted = cipher.encrypt(f.read()) with open("config.enc", "wb") as f: f.write(encrypted) # 解密使用 with open("config.enc", "rb") as f: decrypted = cipher.decrypt(f.read())

    系统学习路径建议

    一、分阶段学习计划

    阶段1:基础入门(1-2周)
    • HTTP协议基础(请求/响应/状态码)
    • requests库基础用法
    • BeautifulSoup解析HTML
    • 数据保存至CSV/JSON
    阶段2:进阶提升(2-3周)
    • XPath高级用法
    • Selenium动态页面处理
    • 反爬机制应对策略
    • Scrapy框架基础
    阶段3:项目实战(3-4周)
    • 完成3个完整项目(招聘/电商/舆情)
    • 集成数据库存储
    • 构建监控告警系统
    • 部署定时任务
    阶段4:高级优化(持续)
    • 分布式爬虫(Scrapy-Redis)
    • 机器学习反反爬
    • 大数据存储方案
    • 云服务器部署

    推荐学习资源:

    • 官方文档:requests、BeautifulSoup、Scrapy
    • 开源项目:github.com/Python3WebSpider
    • 实战教程:《Python网络数据采集》

    二、常见问题速查

    问题现象 可能原因 解决方案
    403 Forbidden User-Agent被识别 更换真实UA + 添加Referer
    页面空白 JavaScript动态渲染 Selenium或分析XHR接口
    数据缺失 请求参数不全 检查Cookie/Token参数
    程序卡死 请求无超时 添加timeout参数 + 异常处理