Python爬虫入门:从基础到实战
1. 爬虫技术概述与基础准备网络爬虫本质上是一个自动化程序它模拟人类浏览网页的行为从互联网上抓取所需数据。与人工操作浏览器不同爬虫能够以更高的效率和更低的成本完成数据采集任务。在开始编写爬虫之前我们需要明确几个关键概念目标数据确定你要采集的数据类型文本、图片、视频等和数据来源特定网站或全网采集频率根据网站规模和更新速度制定合理的采集计划合法性遵守robots.txt协议和网站使用条款1.1 开发环境搭建Python是爬虫开发的首选语言主要因为其丰富的库支持和简洁的语法。推荐使用以下工具链# 创建虚拟环境 python -m venv spider_env source spider_env/bin/activate # Linux/Mac spider_env\Scripts\activate # Windows # 安装核心库 pip install requests beautifulsoup4 lxml对于初学者建议从简单的静态网页抓取开始。静态网页的特点是页面内容直接包含在HTML源码中不需要执行JavaScript就能获取完整数据。我们可以通过浏览器开发者工具F12查看网页结构确定目标数据的位置。2. 基础爬虫实现与核心技巧2.1 HTTP请求基础爬虫工作的第一步是向目标服务器发送HTTP请求。Python中最常用的请求库是requests它比标准库urllib更加友好import requests # 基本GET请求 response requests.get(http://example.com) print(response.status_code) # 状态码 print(response.text) # 响应内容 print(response.headers) # 响应头 # 带参数的GET请求 params {key1: value1, key2: value2} response requests.get(http://example.com/api, paramsparams) # POST请求 data {username: admin, password: 123456} response requests.post(http://example.com/login, datadata)注意实际项目中不要硬编码敏感信息应该使用环境变量或配置文件管理凭证2.2 数据解析技术获取网页内容后我们需要从中提取有用的信息。常用的解析方式有三种正则表达式适合处理有固定模式的文本import re pattern rtitle(.*?)/title title re.search(pattern, html_content).group(1)BeautifulSoup适合处理复杂的HTML文档from bs4 import BeautifulSoup soup BeautifulSoup(html_content, lxml) titles [h2.text for h2 in soup.select(h2.article-title)]XPath适合精确提取特定节点from lxml import etree tree etree.HTML(html_content) price tree.xpath(//span[classprice]/text())[0]2.3 反爬虫应对策略现代网站通常会部署各种反爬虫机制我们需要掌握基本的应对方法反爬虫类型应对策略实现示例IP限制使用代理IPrequests.get(url, proxies{http:http://proxy_ip:port})User-Agent检测随机更换UAheaders {User-Agent: Mozilla/5.0...}请求频率限制添加延迟time.sleep(random.uniform(1,3))验证码自动识别服务接入打码平台API动态加载渲染JS使用Selenium/Puppeteer一个完整的请求头伪装示例headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36, Accept-Language: zh-CN,zh;q0.9, Referer: http://example.com/, Cookie: session_idxxxxxx }3. 实战项目豆瓣图书爬虫3.1 项目分析我们以豆瓣图书Top250为例构建一个完整的爬虫项目。目标数据包括图书名称作者/译者信息评分和评价人数出版信息价格通过分析页面结构我们发现数据呈现规律每页显示25本书分页参数为start数据主要包含在div classinfo中3.2 代码实现import requests from bs4 import BeautifulSoup import time import random import csv def get_book_info(url): headers {User-Agent: Mozilla/5.0} response requests.get(url, headersheaders) soup BeautifulSoup(response.text, lxml) books [] for item in soup.find_all(div, class_info): title item.find(a).get_text(stripTrue) pub_info item.find(div, class_pub).get_text(stripTrue) rating item.find(span, class_rating_nums).get_text(stripTrue) people item.find(span, class_pl).get_text(stripTrue)[3:-4] books.append({ title: title, pub_info: pub_info, rating: rating, people: people }) return books def main(): base_url https://book.douban.com/top250?start all_books [] for i in range(0, 250, 25): url base_url str(i) books get_book_info(url) all_books.extend(books) print(f已获取第{i//251}页数据) time.sleep(random.uniform(1, 3)) # 随机延迟 # 保存数据 with open(douban_books.csv, w, newline, encodingutf-8) as f: writer csv.DictWriter(f, fieldnames[title, pub_info, rating, people]) writer.writeheader() writer.writerows(all_books) if __name__ __main__: main()3.3 项目优化建议异常处理增加网络请求重试机制from retrying import retry retry(stop_max_attempt_number3, wait_fixed2000) def safe_request(url): try: return requests.get(url, timeout10) except Exception as e: print(f请求失败: {e}) raise数据存储考虑使用数据库而非CSVimport sqlite3 conn sqlite3.connect(books.db) c conn.cursor() c.execute(CREATE TABLE IF NOT EXISTS books (title text, pub_info text, rating real, people integer))分布式扩展使用Scrapy-Redis实现分布式爬取4. 爬虫进阶与伦理考量4.1 高级技术方案当面对更复杂的爬取需求时可能需要以下技术动态页面渲染使用Selenium或Playwrightfrom selenium import webdriver driver webdriver.Chrome() driver.get(https://example.com) dynamic_content driver.page_sourceAPI逆向工程分析XHR请求直接调用数据接口import json api_url https://api.example.com/data params {page: 1, size: 20} response requests.get(api_url, paramsparams) data json.loads(response.text)验证码处理使用OCR或机器学习模型import pytesseract from PIL import Image image Image.open(captcha.png) text pytesseract.image_to_string(image)4.2 爬虫伦理与法律在开发爬虫时必须考虑以下伦理和法律问题尊重robots.txt检查目标网站的爬虫协议User-agent: * Disallow: /private/ Crawl-delay: 5控制请求频率避免对服务器造成过大压力import time time.sleep(2) # 每次请求间隔至少2秒数据使用限制遵守网站的使用条款不将数据用于商业用途隐私保护不收集、存储或传播个人隐私信息4.3 常见问题排查以下是爬虫开发中常见问题及解决方案问题现象可能原因解决方案返回403错误IP被封禁更换代理IP或降低请求频率获取空数据动态加载使用Selenium或分析API接口数据乱码编码问题检查响应头Content-Type正确解码连接超时网络问题增加超时时间添加重试机制验证码频繁行为异常模拟人类操作模式添加随机延迟一个实用的调试技巧是保存网页快照with open(debug.html, w, encodingutf-8) as f: f.write(response.text)在实际项目中我建议从简单需求开始逐步增加复杂度。比如先实现单页爬取再处理分页先获取基础数据再处理复杂字段。每次迭代后都进行测试确保爬虫的稳定性和可靠性。