
1. 爬虫基础与工具选型网络爬虫本质上是一种自动化获取网页数据的程序。Python在这个领域具有天然优势得益于其丰富的第三方库和简洁的语法。Requests库负责处理HTTP请求而BeautifulSoup则专注于HTML解析这种组合既轻量又强大特别适合中小规模的爬取任务。我最初接触爬虫时尝试过urllib标准库但发现Requests的API设计明显更人性化。比如处理HTTP基本认证Requests只需要一行auth(user,pass)而urllib需要手动构造授权头。这种设计哲学让开发者能更专注于业务逻辑。重要提示虽然这两个库学习曲线平缓但实际项目中必须考虑反爬机制。建议新手从允许爬取的练习网站开始如books.toscrape.com2. 环境配置与请求处理2.1 安装与基础请求创建虚拟环境是Python项目的最佳实践python -m venv scraper_env source scraper_env/bin/activate # Linux/Mac pip install requests beautifulsoup4发起GET请求的完整参数示例response requests.get( urlhttps://example.com/api, params{page: 2, limit: 50}, headers{ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64), Accept-Language: en-US,en;q0.9 }, timeout10 )这里有几个关键点params会自动编码为查询字符串自定义User-Agent能减少被屏蔽的概率超时设置是生产环境必须项2.2 响应处理进阶检查请求是否成功不应仅看状态码if response.ok: # 状态码200-400 print(response.encoding) # 检测编码 response.encoding utf-8 # 显式设置 html response.text处理重定向时要注意r requests.get(http://github.com, allow_redirectsFalse) print(r.status_code, r.headers[Location])3. HTML解析实战3.1 BeautifulSoup核心用法创建soup对象时的最佳实践from bs4 import BeautifulSoup soup BeautifulSoup(html, lxml) # 需要pip install lxml # 或 soup BeautifulSoup(html, html.parser) # 内置解析器元素查找的几种方式对比# CSS选择器推荐 soup.select(div.product h3.title) # find_all方法 soup.find_all(a, class_external, limit5) # 属性查找 soup.find(attrs{data-id: 123})3.2 数据提取技巧处理相对链接的通用方法from urllib.parse import urljoin base_url https://example.com for link in soup.select(a): absolute_url urljoin(base_url, link[href])提取表格数据的完整示例data [] for row in soup.select(table tr): cols [td.get_text(stripTrue) for td in row.select(td)] if cols: data.append(cols)4. 反爬应对策略4.1 请求头优化模拟浏览器的完整headers配置headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64), Accept: text/html,application/xhtmlxml, Accept-Encoding: gzip, deflate, Connection: keep-alive, Referer: https://www.google.com/ }4.2 请求节奏控制使用time模块实现简单延时import time import random for page in range(1, 6): time.sleep(random.uniform(1, 3)) # 随机延时 # 爬取逻辑...更专业的做法是使用requests.Session保持会话session requests.Session() session.headers.update(headers) session.get(https://example.com/login, auth(user,pass))5. 项目架构建议5.1 代码组织规范推荐的项目结构/scraper /utils logger.py storage.py config.py main.py requirements.txt配置分离示例config.pyBASE_URL https://example.com MAX_RETRIES 3 TIMEOUT 155.2 数据存储方案CSV存储的完整示例import csv with open(output.csv, w, newline, encodingutf-8) as f: writer csv.writer(f) writer.writerow([标题, 价格, 链接]) # 表头 for item in items: writer.writerow([item[title], item[price], item[link]])6. 常见问题排查6.1 编码问题处理当遇到乱码时的诊断流程检查response.encoding查看网页meta标签的charset声明尝试chardet自动检测import chardet encoding chardet.detect(response.content)[encoding]6.2 元素定位失败调试CSS选择器的技巧print(soup.prettify()) # 格式化输出整个文档 temp soup.select_one(div.product) print(temp.attrs) # 查看元素所有属性7. 性能优化技巧7.1 并发请求实现使用concurrent.futures的基本模式from concurrent.futures import ThreadPoolExecutor urls [fhttps://example.com/page/{i} for i in range(1,6)] def fetch(url): return requests.get(url).text with ThreadPoolExecutor(max_workers3) as executor: results list(executor.map(fetch, urls))7.2 缓存机制磁盘缓存实现示例from pathlib import Path import hashlib def get_cache_key(url): return hashlib.md5(url.encode()).hexdigest() def get_from_cache(url): key get_cache_key(url) cache_file Path(fcache/{key}.html) if cache_file.exists(): return cache_file.read_text() return None8. 合法合规要点8.1 robots.txt检查自动解析robots.txt的示例from urllib.robotparser import RobotFileParser rp RobotFileParser() rp.set_url(https://example.com/robots.txt) rp.read() can_scrape rp.can_fetch(MyBot, https://example.com/private)8.2 数据使用规范个人项目应遵守的原则不爬取敏感个人信息遵守网站的Terms of Service控制请求频率明确标注数据来源在实际项目中我通常会添加--delay参数来控制爬取速度比如import argparse parser argparse.ArgumentParser() parser.add_argument(--delay, typefloat, default2.0) args parser.parse_args()