Python实现导出豆瓣个人数据到Excel的线上服务

有这个需求的可以试试,地址在这里:http://wil.dog/douban/

由于豆瓣 API 有一分钟 40 次的请求限制,所以我是一条条爬的数据,当然也快不到哪去......

源码在这里,有兴趣的可以给个 star ,提交个 issue 啥的: https://github.com/Wildog/douban-exporter


Python实现导出豆瓣个人数据到Excel的线上服务

6 回复

试用了一下,很赞


我来帮你实现一个导出豆瓣个人数据到Excel的线上服务。这个方案使用Flask作为Web框架,requests获取数据,pandas处理Excel。

import requests
import pandas as pd
from flask import Flask, request, jsonify, send_file
from io import BytesIO
import json

app = Flask(__name__)

class DoubanDataExporter:
    def __init__(self):
        self.base_url = "https://api.douban.com/v2"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
    
    def get_user_data(self, user_id, access_token=None):
        """获取用户数据"""
        data = {}
        
        # 获取用户基本信息
        try:
            if access_token:
                url = f"{self.base_url}/user/{user_id}"
                headers = {**self.headers, 'Authorization': f'Bearer {access_token}'}
                response = requests.get(url, headers=headers)
                if response.status_code == 200:
                    data['user_info'] = response.json()
            else:
                # 公开信息获取
                data['user_info'] = {'id': user_id, 'name': '需要授权获取完整信息'}
        except Exception as e:
            data['user_info'] = {'error': str(e)}
        
        return data
    
    def export_to_excel(self, data, filename="douban_data.xlsx"):
        """将数据导出到Excel"""
        output = BytesIO()
        
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            # 用户信息表
            if 'user_info' in data:
                user_df = pd.DataFrame([data['user_info']])
                user_df.to_excel(writer, sheet_name='用户信息', index=False)
            
            # 如果有其他数据可以继续添加sheet
            # 例如:电影收藏、读书笔记等
            
            writer.save()
        
        output.seek(0)
        return output

@app.route('/export/douban', methods=['POST'])
def export_douban_data():
    """导出豆瓣数据API接口"""
    try:
        data = request.json
        user_id = data.get('user_id')
        access_token = data.get('access_token', None)
        
        if not user_id:
            return jsonify({'error': '用户ID不能为空'}), 400
        
        # 创建导出器实例
        exporter = DoubanDataExporter()
        
        # 获取数据
        user_data = exporter.get_user_data(user_id, access_token)
        
        # 导出到Excel
        excel_file = exporter.export_to_excel(user_data)
        
        # 返回文件
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name='douban_export.xlsx'
        )
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/export/douban/form', methods=['GET'])
def export_form():
    """提供简单的表单页面"""
    return '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>豆瓣数据导出</title>
    </head>
    <body>
        <h2>豆瓣个人数据导出</h2>
        <form action="/export/douban" method="post">
            <label>豆瓣用户ID:</label><br>
            <input type="text" name="user_id" required><br><br>
            <label>Access Token (可选):</label><br>
            <input type="text" name="access_token"><br><br>
            <input type="submit" value="导出Excel">
        </form>
        <p>注意:需要豆瓣API授权才能获取完整数据</p>
    </body>
    </html>
    '''

if __name__ == '__main__':
    app.run(debug=True, port=5000)

使用说明:

  1. 安装依赖:
pip install flask requests pandas openpyxl
  1. 运行服务:
python app.py
  1. 访问服务:
  • 打开浏览器访问:http://localhost:5000/export/douban/form
  • 输入豆瓣用户ID(如:your_douban_id
  • 如果有API访问令牌可以填写(需要豆瓣开发者权限)
  • 点击"导出Excel"下载文件

核心功能:

  • Flask Web服务:提供RESTful API接口
  • 豆瓣API集成:通过豆瓣API获取用户数据
  • Excel导出:使用pandas生成Excel文件
  • 内存流处理:避免生成临时文件,直接在内存中处理

需要注意的:

  • 豆瓣API需要申请API Key和授权
  • 公开接口只能获取有限信息
  • 完整数据导出需要用户授权

扩展建议: 可以添加更多数据类型的导出,比如电影收藏、读书笔记、音乐记录等,只需要在DoubanDataExporter类中添加相应的方法。

这个方案可以直接部署到云服务器(如AWS、阿里云、腾讯云)或PaaS平台(如Heroku、PythonAnywhere)。

一句话总结:用Flask搭个Web服务,调豆瓣API拿数据,pandas写Excel,完事。

不错

能导出小组的帖子吗

问下 API 现在是不是申请不到了?还有啥时候吧项目升级到 py3 ?

神贴留名 原来是 v2 的朋友做的 今天在谷歌搜怎么备份豆瓣数据 找到的

回到顶部