Python爬虫入门 - 从零开始的爬虫学习之旅

网络爬虫是互联网时代最重要的数据获取技术之一。本文将从最基础的知识开始,由浅入深地带你走进爬虫的世界。理解HTTP协议和HTML基本结构对编写高效爬虫至关重要。Python语法简洁、库资源丰富,是爬虫开发的首选语言。

一、为什么选择Python进行爬虫开发

1. 语法简洁易懂
Python的语法非常接近自然语言,代码可读性高。相比Java、C++等语言,Python可以用更少的代码实现相同的功能,大大提高了开发效率。

2. 丰富的第三方库
Python拥有庞大的第三方库生态系统:

  • requests - 简洁易用的HTTP请求库
  • BeautifulSoup - 强大的HTML/XML解析库
  • lxml - 高性能的解析器
  • Scrapy - 专业的爬虫框架
  • Selenium - 浏览器自动化工具

3. 活跃的社区支持
Python拥有全球最大的开发者社区,遇到问题很容易找到解决方案。

二、开发环境准备

安装必要的Python库:

pip install requests beautifulsoup4 lxml

import requests
import bs4
print("requests版本:", requests.__version__)
print("beautifulsoup版本:", bs4.__version__)

三、第一个爬虫程序

编写一个能够获取网页标题的爬虫程序:

import requests
from bs4 import BeautifulSoup

# 1. 定义目标URL
url = "https://www.example.com"

# 2. 发送HTTP请求
response = requests.get(url)

# 3. 检查请求是否成功
print(f"状态码: {response.status_code}")

# 4. 解析HTML内容
soup = BeautifulSoup(response.text, 'lxml')

# 5. 提取数据
title = soup.find('title').text
print(f"页面标题: {title}")

# 6. 提取所有链接
links = soup.find_all('a')
for link in links[:5]:
    href = link.get('href')
    if href:
        print(f"链接: {href}")

四、requests库详解

4.1 发送GET请求

# 最简单的GET请求
response = requests.get("https://api.github.com/users/octocat")

# 带参数的GET请求
params = {'page': 1, 'per_page': 10}
response = requests.get(url, params=params)

# 检查响应状态
if response.status_code == 200:
    data = response.json()
    print(f"获取到{len(data)}个仓库")

4.2 发送POST请求

# POST请求示例 - 提交表单数据
login_url = "https://www.example.com/login"
form_data = {'username': 'your_username', 'password': 'your_password'}
response = requests.post(login_url, data=form_data)

# 提交JSON数据
import json
json_data = {'title': 'My Post', 'body': 'Content'}
response = requests.post(url, json=json_data)

4.3 设置请求头

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept': 'text/html,application/xhtml+xml',
    'Accept-Language': 'zh-CN,zh;q=0.9',
}
response = requests.get(url, headers=headers)

为什么要设置User-Agent?
很多网站会检查请求头中的User-Agent,如果发现是爬虫,可能会拒绝访问。设置浏览器标识可以伪装成正常用户访问。

4.4 使用Session保持会话

import requests

# 创建Session对象
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0'})

# Session会自动处理Cookie
response = session.get("https://www.example.com/login")
response = session.post("https://www.example.com/do-login", data={'user': 'test'})
# 之后的请求都保持登录状态

4.5 处理响应

response = requests.get(url)

print(response.status_code)       # HTTP状态码
print(response.headers)           # 响应头字典
print(response.text)             # 字符串形式的响应内容
print(response.content)          # 字节形式的响应内容
print(response.json())           # JSON格式的响应
print(response.encoding)         # 响应内容的编码
response.encoding = 'utf-8'     # 手动设置编码

五、异常处理

健壮的爬虫程序需要处理各种可能的异常:

import requests
from requests.exceptions import RequestException, Timeout, ConnectionError

def fetch_url(url, timeout=10):
    try:
        response = requests.get(url, timeout=timeout)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        return response.text
    except Timeout:
        print(f"请求超时: {url}")
        return None
    except ConnectionError:
        print(f"连接错误: {url}")
        return None
    except RequestException as e:
        print(f"请求异常: {e}")
        return None

六、实践案例:爬取新闻标题

import requests
from bs4 import BeautifulSoup
import time

def crawl_news_titles(base_url, pages=3):
    all_titles = []
    for page in range(1, pages + 1):
        if page == 1:
            url = base_url
        else:
            url = f"{base_url}?page={page}"
        try:
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            soup = BeautifulSoup(response.text, 'lxml')
            titles = soup.select('.news-title, .title, h1, h2')
            for title in titles:
                text = title.text.strip()
                if text and len(text) > 5:
                    all_titles.append(text)
            print(f"第{page}页: 获取{len(titles)}个标题")
            time.sleep(1)  # 礼貌爬取
        except Exception as e:
            print(f"第{page}页爬取失败: {e}")
            continue
    return all_titles

七、总结

本文介绍了Python爬虫开发的基础知识:

  • 爬虫的基本原理和HTTP协议
  • 开发环境搭建和必要库安装
  • requests库发送HTTP请求
  • BeautifulSoup解析HTML
  • 异常处理和错误恢复
  • 实用爬虫案例

下一步学习:

  • BeautifulSoup进阶:CSS选择器
  • 正则表达式:精确提取数据
  • Selenium:爬取JavaScript渲染的页面
  • Scrapy框架:专业大规模爬虫
  • 数据存储:JSON、CSV、MySQL、MongoDB

注意事项:

  • 遵守网站的robots.txt协议
  • 控制请求频率,避免给服务器造成压力
  • 尊重版权,不要爬取受保护的内容
  • 在合法合规的前提下使用爬虫技术

掌握以上内容,你已经具备了编写简单爬虫的能力!

发表回复

后才能评论