Python爬虫入门教程:从零开始掌握网络爬虫技术

什么是网络爬虫?

网络爬虫(Web Crawler),也称为网络蜘蛛或网络机器人,是一种按照一定规则自动抓取互联网信息的程序。爬虫可以自动访问网页、提取数据、保存数据,广泛应用于搜索引擎、数据分析、竞品分析等领域。

为什么选择Python做爬虫?

  • 语法简洁:Python语法简单易学,代码可读性强
  • 生态丰富:拥有众多优秀的爬虫库和框架
  • 社区活跃:遇到问题容易找到解决方案
  • 跨平台:可以在Windows、Linux、macOS上运行

Python爬虫常用库

1. requests - HTTP请求库

requests是Python中最流行的HTTP库,简单易用,支持发送HTTP/HTTPS请求。

import requests

# 发送GET请求
response = requests.get('https://www.example.com')
print(response.text)  # 输出网页内容
print(response.status_code)  # 输出状态码

2. BeautifulSoup - HTML解析库

BeautifulSoup用于解析HTML文档,提取所需数据,简单直观。

from bs4 import BeautifulSoup
import requests

# 获取网页
response = requests.get('https://www.example.com')
soup = BeautifulSoup(response.text, 'html.parser')

# 查找元素
title = soup.find('h1').text  # 查找h1标签
links = soup.find_all('a')  # 查找所有a标签

for link in links:
    print(link.get('href'))  # 输出链接地址

3. lxml - 高性能解析库

lxml是基于C语言开发的解析库,解析速度快,支持XPath和CSS选择器。

from lxml import etree
import requests

# 获取网页
response = requests.get('https://www.example.com')
html = response.text

# 解析HTML
tree = etree.HTML(html)

# 使用XPath提取数据
titles = tree.xpath('//h1/text()')
links = tree.xpath('//a/@href')

4. Scrapy - 爬虫框架

Scrapy是一个强大的爬虫框架,支持异步、中间件、管道等高级功能。

import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'
    start_urls = ['https://www.example.com']

    def parse(self, response):
        # 提取数据
        title = response.css('h1::text').get()
        yield {'title': title}
        
        # 跟踪链接
        for link in response.css('a::attr(href)').getall():
            yield response.follow(link, self.parse)

5. Selenium - 浏览器自动化

Selenium可以模拟真实浏览器操作,适合处理JavaScript渲染的页面。

from selenium import webdriver
from selenium.webdriver.common.by import By

# 启动浏览器
driver = webdriver.Chrome()

# 访问网页
driver.get('https://www.example.com')

# 查找元素
title = driver.find_element(By.TAG_NAME, 'h1').text

# 关闭浏览器
driver.quit()

爬虫基本流程

1. 发送HTTP请求

使用requests或urllib等库发送请求,获取网页内容。注意设置请求头、超时时间、代理等。

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}

params = {
    'page': 1,
    'size': 10
}

response = requests.get(
    'https://www.example.com/api',
    headers=headers,
    params=params,
    timeout=10
)

2. 解析网页内容

使用BeautifulSoup、lxml或正则表达式解析HTML,提取所需数据。

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, 'html.parser')

# 提取标题
title = soup.find('h1', class_='title').text

# 提取价格
price = soup.find('span', class_='price').text

# 提取列表
items = soup.find_all('div', class_='item')
for item in items:
    print(item.find('a').text)

3. 数据清洗与存储

清洗提取的数据,去除空白、特殊字符等,然后保存到文件或数据库。

import json
import csv

# 保存为JSON
data = {'title': title, 'price': price}
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 保存为CSV
with open('data.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['标题', '价格'])
    writer.writerow([title, price])

4. 异常处理与重试

网络请求可能失败,需要做好异常处理和重试机制。

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# 配置重试策略
session = requests.Session()
retry = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

# 发送请求
try:
    response = session.get('https://www.example.com', timeout=10)
    response.raise_for_status()
except requests.RequestException as e:
    print(f'请求失败: {e}')

爬虫实战案例

案例:爬取豆瓣电影Top250

import requests
from bs4 import BeautifulSoup
import csv

def get_movie_list(page):
    url = f'https://movie.douban.com/top250?start={page * 25}'
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    movies = []
    items = soup.find_all('div', class_='item')
    
    for item in items:
        title = item.find('span', class_='title').text
        rating = item.find('span', class_='rating_num').text
        info = item.find('div', class_='bd').p.text.strip()
        
        movies.append({
            'title': title,
            'rating': rating,
            'info': info
        })
    
    return movies

# 爬取所有页面
all_movies = []
for page in range(10):
    movies = get_movie_list(page)
    all_movies.extend(movies)
    print(f'已爬取第{page+1}页')

# 保存数据
with open('douban_top250.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['title', 'rating', 'info'])
    writer.writeheader()
    writer.writerows(all_movies)

print(f'爬取完成,共{len(all_movies)}部电影')

反爬虫与应对策略

1. User-Agent检测

网站通过User-Agent识别爬虫,需要设置合理的User-Agent。

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}

2. IP限制

网站可能限制IP访问频率,可以使用代理IP池。

proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}

response = requests.get(url, proxies=proxies)

3. 登录验证

需要登录的网站,可以使用session保持登录状态。

session = requests.Session()
session.post('https://www.example.com/login', data={
    'username': 'your_username',
    'password': 'your_password'
})

# 后续请求保持登录状态
response = session.get('https://www.example.com/user/profile')

4. 验证码

遇到验证码,可以使用OCR识别或打码平台。

5. JavaScript渲染

对于动态加载的内容,使用Selenium或Playwright等工具。

爬虫道德规范

  • 遵守robots.txt:检查网站的robots.txt文件,遵守爬虫规则
  • 控制频率:避免频繁请求,给服务器造成压力
  • 尊重版权:爬取的数据不要用于商业用途
  • 保护隐私:不要爬取个人隐私信息

总结

Python爬虫是一门实用的技术,可以帮助我们获取网络上的各种数据。从简单的requests+BeautifulSoup开始,逐步掌握更多高级技巧。记住要在合法合规的前提下使用爬虫技术,做一个有道德的爬虫开发者!

祝大家爬虫学习顺利,早日成为爬虫高手!

发表回复

后才能评论