律师助手(爬虫和处理脚本部分)

在本次技术实践中,我主要编写了一个爬虫程序,用于爬取国家法律法规数据库的相关数据。之后对这些数据进行处理并上传到数据库。需要强调的是,以下所有内容仅用于学习交流。

一、项目概述

本次爬虫项目涉及多个功能模块,分别处理数据库连接、信息状态映射、网络重试、数据库插入、数据总页数获取、单条数据获取、不同法律类型爬取以及宪法内容爬取等任务。下面将详细介绍各个模块的实现。

二、代码实现与模块解析

1. 数据库配置与连接

import requests
import time
import math
import pymysql
import io
import json
from datetime import datetime
from urllib.parse import urljoin
import random

# 数据库配置
DB_CONFIG = {
    #自己的数据库配置
}

# 请求配置
headers = {
    # 自己的请求头配置
}

base_url = 'https://flk.npc.gov.cn/api/'
types = ['flfg', 'xzfg', 'jcfg', 'sfjs', 'dfxfg']
MAX_RETRIES = 5  # 最大重试次数
BASE_DELAY = 3   # 基础延迟时间(秒)
TIMEOUT = 30     # 请求超时时间

def get_db_connection():
    """获取数据库连接"""
    return pymysql.connect(**DB_CONFIG)

此部分代码主要完成了数据库和请求的基础配置,同时定义了获取数据库连接的函数,为后续的数据存储提供了基础。

2. 带重试机制的请求函数

def safe_request(url, method='get', data=None, params=None, retry=0):
    """
    带重试机制的请求函数
    解决JSON解析错误问题
    """
    try:
        if method.lower() == 'get':
            response = requests.get(
                url,
                headers=headers,
                params=params,
                timeout=TIMEOUT
            )
        else:
            headers_post = headers.copy()
            headers_post['Content-Type'] = 'application/x-www-form-urlencoded'
            response = requests.post(
                url,
                headers=headers_post,
                data=data,
                timeout=TIMEOUT
            )
        
        # 检查响应内容是否为JSON
        if 'application/json' not in response.headers.get('Content-Type', '').lower():
            raise ValueError("响应不是JSON格式")
        
        response.raise_for_status()
        return response.json()  # 直接返回解析后的JSON
    
    except (requests.exceptions.RequestException, ValueError, json.JSONDecodeError) as e:
        if retry < MAX_RETRIES:
            wait_time = BASE_DELAY * (2 ** retry) + random.uniform(0, 1)
            print(f"请求失败,{wait_time:.1f}秒后重试... (错误: {str(e)})")
            time.sleep(wait_time)
            return safe_request(url, method, data, params, retry + 1)
        raise Exception(f"请求失败,已达最大重试次数: {str(e)}")

为应对网络不稳定的情况,该函数实现了请求重试机制。若请求失败或响应非 JSON 格式,会进行多次重试,直至达到最大重试次数。

3. 信息状态映射

def get_status_mapping(code):
    """根据状态码返回状态文本"""
    status_map = {
        "1": "有效",
        "5": "已修改",
        "9": "已废止",
        "3": "尚未生效"
    }
    return status_map.get(code, "未知状态")

这个函数用于将法律条目的状态码映射为具体的状态文本,方便后续的数据处理和展示。

4. 带重试机制的文件下载

def download_file_with_retry(url, max_size=50*1024*1024):
    """
    带重试机制的文件下载
    返回文件内容和文件类型
    """
    for attempt in range(MAX_RETRIES):
        try:
            response = requests.get(
                url,
                headers=headers,
                stream=True,
                timeout=TIMEOUT
            )
            response.raise_for_status()
            
            # 检查文件大小
            file_size = int(response.headers.get('Content-Length', 0))
            if file_size > max_size:
                raise ValueError(f"文件过大({file_size}字节),超过{max_size}字节限制")
            
            # 分块读取内容
            file_content = b''
            for chunk in response.iter_content(chunk_size=8192):
                file_content += chunk
                if len(file_content) > max_size:
                    raise ValueError(f"文件超过大小限制({max_size}字节)")
            
            # 确定文件类型
            content_type = response.headers.get('Content-Type', '').lower()
            if 'pdf' in content_type:
                file_type = 'pdf'
            elif 'word' in content_type or 'msword' in content_type:
                file_type = 'word'
            else:
                # 根据URL后缀判断
                ext = url.split('.')[-1].lower()
                file_type = ext if ext in ['pdf', 'docx', 'doc'] else 'unknown'
            
            return file_content, file_type
            
        except requests.exceptions.RequestException as e:
            if attempt == MAX_RETRIES - 1:
                raise
            time.sleep(BASE_DELAY * (attempt + 1))
    
    raise Exception("文件下载失败")

该函数实现了文件下载的重试机制,同时会对文件大小进行检查,避免下载过大的文件。

5. 数据保存到数据库

def save_to_database(data):
    conn = None
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 处理 publish_date
            publish_date = data.get('publish')
            if publish_date == "":  # 如果是空字符串,设为 NULL
                publish_date = None
            sql = """
            INSERT INTO law (title, enacting_authority, legal_nature, 
                            validity_status, publish_date, content, 
                            file_content, file_type)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            """
            cursor.execute(sql, (
                data.get('title', '无标题'),
                data.get('office', '未知机关'),
                data.get('type', '未知类型'),
                data.get('status', '未知状态'),
                publish_date,  # 可能是 NULL 或有效日期
                data.get('content', ''),
                data.get('file_content'),
                data.get('file_type', 'unknown')
            ))
        conn.commit()
        print(f"成功保存: {data.get('title')}")
        return True
    except pymysql.Error as e:
        print(f"数据库错误: {e}")
        if conn:
            conn.rollback()
        return False
    finally:
        if conn:
            conn.close()

在将数据插入数据库时,对公布时间进行了格式验证。若公布时间为空字符串,则将其设为 NULL,避免了之前遇到的 mysql1292 错误。

6. 获取数据总页数

def get_total_pages(t, size=10):
    """获取总页数(增强错误处理)"""
    params = {
        'type': t,
      'searchType': 'title;vague',
      'sortTr': 'f_bbrq_s;desc',
        'gbrqStart': '',
        'gbrqEnd': '',
      'sxrqStart': '',
      'sxrqEnd': '',
        'sort': 'true',
        'page': '1',
        'size': str(size),
        '_': str(int(time.time() * 1000))
    }
    
    try:
        result = safe_request(base_url, params=params)
        total_sizes = result['result']['totalSizes']
        pages = math.ceil(total_sizes / size)
        print(f"{t}类型总页数: {pages}")
        return pages
    except Exception as e:
        print(f"获取{t}类型总页数失败: {e}")
        return 0

该函数用于获取指定类型数据的总页数,同时对可能出现的异常进行了处理。

7. 处理单个法律条目

def process_law_item(item):
    """处理单个法律条目"""
    try:
        # 获取详情
        detail_url = urljoin(base_url, 'detail')
        detail_data = {'id': item['id']}
        
        try:
            detail_json = safe_request(detail_url, method='post', data=detail_data)
        except Exception as e:
            print(f"获取详情失败: {str(e)}")
            return False
        
        if not detail_json.get('result', {}).get('body'):
            print(f"{item.get('title')} 无详情内容")
            return False
            
        body = detail_json['result']['body'][0]
        file_path = body.get('path', '')
        
        if not file_path:
            print(f"{item.get('title')} 无文件路径")
            return False
            
        file_url = urljoin('https://wb.flk.npc.gov.cn', file_path)
        
        # 下载文件
        try:
            file_content, file_type = download_file_with_retry(file_url)
        except Exception as e:
            print(f"下载文件失败: {str(e)}")
            return False
            
        # 准备数据
        law_data = {
            'title': item.get('title', '无标题'),
            'office': item.get('office', '未知机关'),
            'publish': item.get('publish'),
            'type': item.get('type', '未知类型'),
            'status': get_status_mapping(item.get('status', '')),
            'content': f"文件类型: {file_type}", 
            'file_content': file_content,
            'file_type': file_type
        }
        
        # 保存到数据库
        if not save_to_database(law_data):
            return False
            
        # 随机延迟防止被封
        time.sleep(random.uniform(1, 3))
        return True
        
    except Exception as e:
        print(f"处理条目失败: {str(e)}")
        return False

此函数用于处理单个法律条目的详情获取、文件下载和数据保存等操作,同时进行了一系列的错误处理。

8. 爬取指定类型数据

def crawl_type(t, size=10):
    """爬取指定类型数据"""
    total_pages = get_total_pages(t, size)
    if total_pages == 0:
        print(f"{t}类型获取页数失败,跳过")
        return

    print(f"开始爬取{t}类型,共{total_pages}页...")
    
    for page in range(1, total_pages + 1):
        print(f"正在处理第{page}/{total_pages}页...")
        
        params = {
            'type': t,
          'searchType': 'title;vague',
          'sortTr': 'f_bbrq_s;desc',
            'gbrqStart': '',
            'gbrqEnd': '',
          'sxrqStart': '',
          'sxrqEnd': '',
            'sort': 'true',
            'page': str(page),
            'size': str(size),
            '_': str(int(time.time() * 1000))
        }
        
        try:
            # 获取列表数据
            result = safe_request(base_url, params=params)
            data = result['result']['data']
            
            # 处理每个条目
            for item in data:
                if not process_law_item(item):
                    continue
                    
        except Exception as e:
            print(f"第{page}页处理失败: {str(e)}")
            continue

该函数用于爬取指定类型的法律数据,会遍历所有页面并处理每个条目。

9. 爬取宪法数据

def crawl_xf():
    """爬取宪法数据"""
    print("开始爬取宪法数据...")
    url = urljoin(base_url, 'xf')
    
    try:
        result = safe_request(url)
        data = result['result']['data']
        
        for item in data[:7]:  # 只取前7条
            # 获取详情
            detail_url = urljoin(base_url, 'detail')
            detail_data = {'id': item['id']}
            
            try:
                detail_json = safe_request(detail_url, method='post', data=detail_data)
            except Exception as e:
                print(f"获取宪法详情失败: {str(e)}")
                continue
                
            if not detail_json.get('result', {}).get('body'):
                print(f"{item.get('title')} 无详情内容")
                continue
                
            body = detail_json['result']['body'][0]
            file_path = body.get('path', '')
            
            if not file_path:
                print(f"{item.get('title')} 无文件路径")
                continue
                
            file_url = urljoin('https://wb.flk.npc.gov.cn', file_path)
            
            # 下载文件
            try:
                file_content, file_type = download_file_with_retry(file_url)
            except Exception as e:
                print(f"下载宪法文件失败: {str(e)}")
                continue
                
            # 准备数据
            law_data = {
                'title': item.get('title', '无标题'),
                'office': '全国人民代表大会',
                'publish': item.get('publish'),
                'type': item.get('type', '宪法'),
                'status': '有效',
                'content': f"宪法文件类型: {file_type}",
                'file_content': file_content,
                'file_type': file_type
            }
            
            save_to_database(law_data)
            time.sleep(random.uniform(1, 3))
                
    except Exception as e:
        print(f"获取宪法数据失败: {str(e)}")

由于宪法数据内容较少且与其他类型有所不同,因此单独编写了一个函数进行爬取。

10. 主程序

if __name__ == "__main__":
    # 检查数据库表结构
    conn = None
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 确保表存在且有file_content和file_type字段
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS law (
                    id BIGINT PRIMARY KEY AUTO_INCREMENT,
                    title VARCHAR(255) NOT NULL,
                    enacting_authority VARCHAR(100) NOT NULL,
                    legal_nature VARCHAR(50) NOT NULL,
                    validity_status VARCHAR(20) NULL,
                    publish_date DATE NULL,
                    content TEXT,
                    file_content LONGBLOB,
                    file_type VARCHAR(10),
                    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
            """)
        conn.commit()
    except Exception as e:
        print(f"数据库初始化失败: {e}")
        exit()
    finally:
        if conn:
            conn.close()

    # 设置每页数量
    page_size = 10

    # 爬取各类数据
    for t in types:
        crawl_type(t, page_size)

    # 爬取宪法数据
    crawl_xf()

    print("所有数据爬取完成!")

主程序部分会先检查数据库表结构,然后依次爬取各类法律数据和宪法数据。

三、项目经验总结

在项目开发过程中,细致和耐心至关重要。网页数据往往会出现各种意外情况,不能想当然地进行处理,需要对可能出现的问题进行充分的考虑和应对。

此外,在爬取过程中也遇到了一些问题。例如,地方性法规的内容量巨大,50G 的数据库远远不够存储。后续需要思考如何解决存储问题,以及如何突破中国裁判文书网的反爬机制进行数据爬取。

通过这次项目实践,我不仅提升了爬虫开发的技能,也更加深刻地认识到了数据处理和错误处理的重要性。未来,我将继续优化这个项目,解决遇到的问题,同时探索更多有趣的技术应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值