diff --git a/courses/course_database.db b/courses/course_database.db index 90f74a6..08a2dd3 100644 Binary files a/courses/course_database.db and b/courses/course_database.db differ diff --git a/courses/json_parser_songyi.ipynb b/courses/json_parser_songyi.ipynb new file mode 100644 index 0000000..d0804ec --- /dev/null +++ b/courses/json_parser_songyi.ipynb @@ -0,0 +1,224 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 爬取定投课堂资料\n", + "通过解析课程json文件,获取对应资源的url从而下载所有资料\n", + "获取课程id" + ] + }, + { + "cell_type": "code", + "metadata": { + "ExecuteTime": { + "end_time": "2024-05-29T15:37:39.557144Z", + "start_time": "2024-05-29T15:37:30.822604Z" + } + }, + "source": [ + "import json\n", + "import time\n", + "\n", + "import requests\n", + "from IPython.display import Audio,display\n", + "from pydub import AudioSegment\n", + "import os\n", + "import random\n", + "import sqlite3\n", + "\n", + "# with open('audio.json', encoding=\"UTF-8\") as f:\n", + "# json_data = json.load(f)\n", + "# print(type(json_data[1])) # Output: dict\n", + "# TODO: 优化代码\n", + "\n", + "# get audio form database\n", + "id = 491\n", + "conn = sqlite3.connect('course_database.db')\n", + "cursor = conn.cursor()\n", + "audio_data = cursor.execute('select JSON from JSON_DATA jd where id = ?', (id,)).fetchall()\n", + "# json_data = cursor.fetchall()[0][0]\n", + "json_string = audio_data[0][0] if audio_data else None\n", + "cursor.close()\n", + "conn.close()\n", + "json_data = json.loads(json_string)\n", + "\n", + "# course_id = str(json_data[1]['course_id'])\n", + "course_title = json_data[\"data\"][\"title\"].replace(\".\", \"_\").replace(\"/\", \"_\")\n", + "os.makedirs(course_title, exist_ok=True)\n", + "\n", + "# 遍历\n", + "audio_list = []\n", + "for audio in json_data['data']['course_contents']:\n", + " # t = random.randint(1, 10)\n", + " # time.sleep(1)\n", + " category = audio['category']\n", + " # requests.adapters.DEFAULT_RETRIES = 100\n", + " # 获取音频内容\n", + " i = 1\n", + " while i >= 1:\n", + " try:\n", + " if category == \"audio\":\n", + " url = audio['attachment']['url']\n", + " audio = requests.get(url)\n", + " audio_list.append(audio.content)\n", + " # 获取文本笔记\n", + " elif category == \"text\":\n", + " text = audio['content']\n", + " print(text)\n", + " with open(os.path.join(course_title, course_title + 'note.txt'), 'a') as file:\n", + " file.write(text)\n", + " file.write(\"\\n\")\n", + " # 获取其他可下载附件\n", + " elif category != \"MESSAGE_RECALL\":\n", + " # print(audio['category'])\n", + " if 'attachment' in audio:\n", + " url = audio['attachment']['url']\n", + " attachment = requests.get(url)\n", + " filename = os.path.basename(url)\n", + " with open(os.path.join(course_title, filename), 'wb') as file:\n", + " file.write(attachment.content)\n", + " # 获取其他内容\n", + " else:\n", + " print(audio['category'])\n", + " if 'attachment' in audio:\n", + " print(audio['attachment']['url'])\n", + " print(audio['text'])\n", + " i = 0\n", + " except:\n", + " i += 1\n", + " print(\"get file failed\")\n", + " if 'attachment' in audio:\n", + " print(audio['attachment']['url'])\n", + "\n", + "# 处理获取所有音频文件\n", + "audio_seg_list = []\n", + "try:\n", + " for i in audio_list:\n", + " with open('temp.mp3', 'wb') as file:\n", + " file.write(i) # 确保i是二进制数据\n", + " audio_part = AudioSegment.from_mp3('temp.mp3')\n", + " audio_seg_list.append(audio_part)\n", + " \n", + " x = sum(audio_seg_list)\n", + " audio_name = course_title + '/' + course_title + '.mp3'\n", + " x.export(audio_name, format=\"mp3\")\n", + " display(Audio(audio_name))\n", + "except Exception as e:\n", + " print(\"合并音频时发生错误:\", e)" + ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "例行公事\n", + "daily routine\n", + "睡觉 吃/排\n" + ] + }, + { + "data": { + "text/plain": [ + "" + ], + "text/html": [ + "\n", + " \n", + " " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "execution_count": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 获取图片url" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2023-07-05T10:56:34.184660400Z", + "start_time": "2023-07-05T10:56:34.073384900Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "https://xuexi-courses-storage.firesbox.com/7000102069/replay/78b6da46-ecd8-46fb-a857-423ca6da8196.png\n" + ] + } + ], + "source": [ + "# get all url and text\n", + "import json\n", + "import requests\n", + "from IPython.display import Audio,display\n", + "from pydub import AudioSegment\n", + "import os\n", + "\n", + "# get pic url list\n", + "\n", + "\n", + "with open('audio.json', encoding= \"UTF-8\") as f:\n", + " json_data = json.load(f)\n", + "# print(type(json_data[1])) # Output: dict\n", + "\n", + "course_title = str(json_data[1]['course_title'])\n", + "# os.makedirs(course_title, exist_ok=True)\n", + "\n", + "audio_list = []\n", + "for audio in json_data:\n", + " category = audio['category']\n", + " if category == \"PLAIN_IMAGE\":\n", + " url = audio['attachment']['url']\n", + " print(url)\n", + " # with open( course_title + '_pic_url.txt', 'a') as file:\n", + " # file.write(url)\n", + " # file.write(\"\\n\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.6" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/courses/parse_course.py b/courses/parse_course.py index 1b9097b..93cc57b 100644 --- a/courses/parse_course.py +++ b/courses/parse_course.py @@ -128,14 +128,15 @@ def query_course_by_id(course_id): # return re.sub(r'[\r\n]', '', str(all_course_json[0])) return all_course_json[0][0] + # 保存课程json数据文件到数据库 def save_course_json(ids): conn = sqlite3.connect('course_database.db') print("数据库打开成功") c = conn.cursor() for id in ids: - if id > 7: - continue + # if id > 7: + # continue token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIxMDAwMDgzNDciLCJleHAiOjE3MTkxODk0ODQsImp0aSI6IjU3ZTJhMzdmLTMyZGEtNGQ2My1hZjQxLTY5NTRlNmU1OTg2MiIsImlhdCI6MTcxNjUxMTA4NCwiaXNzIjoiYXBwdXNlciIsInVpZCI6ImJlMmViOGIyLTFhOTItNGVmMC05ZDAwLTA1YTlkN2E2OWRiMiIsInNjaGVtZSI6Imp3dGhzIiwic2lkIjoiMWI4ZjE1ZTItYjQ5ZC00MmRmLWEwNDUtZmQxYTUwNzI5ZjkxIn0.IO7C2gtsi8lMdrOgWGNuxK-t2zzmDPvmI4BqISHeZEI" json_data = request_date(id, token) title = json_data["data"]["title"].replace(".", "_").replace("/", "_") @@ -143,7 +144,8 @@ def save_course_json(ids): updated_at = datetime.fromisoformat(json_data["data"]["updated_at"].replace('Z', '+00:00')) # 插入JSON字符串到SQLite表中 - c.execute("INSERT OR IGNORE INTO JSON_DATA (ID,JSON,TYPE,REMARK,CREATED_AT,UPDATED_AT) VALUES (?,?,?,?,?,?)", (id,json.dumps(json_data),"COURSE",title,created_at,updated_at)) + c.execute("INSERT OR IGNORE INTO JSON_DATA (ID,JSON,TYPE,REMARK,CREATED_AT,UPDATED_AT) VALUES (?,?,?,?,?,?)", + (id, json.dumps(json_data), "COURSE", title, created_at, updated_at)) conn.commit() secs = random.normalvariate(1, 0.4) if secs <= 0: @@ -151,12 +153,14 @@ def save_course_json(ids): sleep(secs) conn.close() + if __name__ == '__main__': - ids = get_course_id('all/course.json') + # ids = get_course_id('all/course.json') token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIxMDAwMDgzNDciLCJleHAiOjE3MTkxODk0ODQsImp0aSI6IjU3ZTJhMzdmLTMyZGEtNGQ2My1hZjQxLTY5NTRlNmU1OTg2MiIsImlhdCI6MTcxNjUxMTA4NCwiaXNzIjoiYXBwdXNlciIsInVpZCI6ImJlMmViOGIyLTFhOTItNGVmMC05ZDAwLTA1YTlkN2E2OWRiMiIsInNjaGVtZSI6Imp3dGhzIiwic2lkIjoiMWI4ZjE1ZTItYjQ5ZC00MmRmLWEwNDUtZmQxYTUwNzI5ZjkxIn0.IO7C2gtsi8lMdrOgWGNuxK-t2zzmDPvmI4BqISHeZEI" # json_data = request_date(ids[0], token) # json_data = query_course_by_id(488) # get_audio(json_data) # print(json_data) # get_all_attachments(json_data) + ids = [489, 490, 491] save_course_json(ids) diff --git a/requirements.txt b/requirements.txt index 07296d3..7a9fed2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ requests>=2.31.0 ipython~=8.24.0 Scrapy~=2.11.2 -pydub~=0.25.1 \ No newline at end of file +pydub~=0.25.1 +tqdm~=4.66.4 \ No newline at end of file