</> r0f2 / 技术札记

Python爬虫从入门到实战

更新于 2026-02 Python
Python 爬虫

一、前言:为什么学习爬虫?

在当今数据为王的时代,网络爬虫已成为获取数据的核心技能之一。本文将从最基础的内容讲起,手把手带你掌握Python爬虫的核心技能。

学习爬虫的好处 数据获取能力是数据分析师的基本功,掌握爬虫可以让你不再依赖他人提供的数据,真正做到数据自主。

二、环境准备

首先,确保你的Python环境已经安装。然后使用pip安装必要的库:

# 安装爬虫相关库
pip install requests beautifulsoup4 lxml

# 验证安装
python -c "import requests; print('requests OK')"
python -c "import bs4; print('beautifulsoup4 OK')"
库说明
  • requests - 发送HTTP请求
  • beautifulsoup4 - 解析HTML/XML
  • lxml - 高性能HTML解析器

三、HTTP协议基础

在开始写代码之前,我们需要了解HTTP协议的基本概念:

  • GET请求 - 从服务器获取数据
  • POST请求 - 向服务器提交数据
  • Headers - 请求头,模拟浏览器访问
  • Status Code - 状态码(200成功,404未找到等)

四、使用requests库

requests库是Python最流行的HTTP库,语法简洁易懂:

import requests

# 基本GET请求
response = requests.get('https://www.example.com')
print(f'状态码: {response.status_code}')

# 带参数的请求
params = {'page': 1, 'limit': 10}
response = requests.get('https://api.example.com/items', params=params)

4.1 模拟浏览器访问

很多网站会检测请求头中的User-Agent来防止爬虫,我们需要设置合适的请求头:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept': 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8',
}
response = requests.get('https://www.example.com', headers=headers)
print(response.status_code)

五、HTML解析:BeautifulSoup

获取到网页内容后,我们需要解析HTML来提取想要的数据:

from bs4 import BeautifulSoup

html = '''
<html>
    <body>
        <div class="article">
            <h1>文章标题</h1>
            <p class="content">这是文章内容</p>
        </div>
    </body>
</html>
'''

soup = BeautifulSoup(html, 'lxml')
print(soup.h1.text)

六、实战案例

6.1 爬取简书文章标题

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0'}

url = 'https://www.jianshu.com/'
response = requests.get(url, headers=headers)

soup = BeautifulSoup(response.text, 'lxml')
articles = soup.find_all('a', class_='title')

for i, article in enumerate(articles, 1):
    print(f'{i}. {article.text.strip()}')
注意事项 请勿频繁请求网站,遵守robots.txt协议,本文仅供学习交流使用。

七、常见问题与反爬策略

  • User-Agent检测 - 解决:设置真实的UA
  • IP限制 - 解决:使用代理IP
  • 验证码 - 解决:打码平台或OCR识别
  • 动态加载 - 解决:使用Selenium或Playwright