From 9008b3d31cbdcaf8006a3885c7da3228c2e5a806 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 22 Dec 2020 22:21:57 +0800 Subject: [PATCH 01/27] =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=E7=AC=94=E8=AE=B0=E4=BD=9C=E4=B8=9A=E6=8F=90?= =?UTF-8?q?=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0\350\212\202-\344\275\234\344\270\232.py" | 64 ++++++++ ...17\345\240\202\347\254\224\350\256\260.md" | 152 ++++++++++++++++++ 2 files changed, 216 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..be8a0f24 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,64 @@ +def add(a: int, b: int)-> int: + """ + 加法运算 + """ + return a + b + +def subtract(a:int, b:int)->int: + """ + 减法运算 + """ + return a - b + +def ride(a:int, b:int)-> int: + """ + 乘法运算 + """ + return a * b + +def divide(a:int, b:int)-> int: + """ + 除法运算 + """ + return a / b + +def double_div(a:int, b:int)-> int: + """ + 整除运算 + """ + return a // b + +def surplus(a:int, b:int)-> float: + """ + 取余运算 + """ + return a % b + +def excract(a:int, b:int)-> None: + """ + 开方运算 + """ + return a**b + + +if __name__ == "__main__": + result1 = add(1, 2) + print(result1) + + result2 = subtract(5, 2) + print(result2) + + result3 = ride(3, 2) + print(result3) + + result4 = divide(5, 2) + print(result4) + + result5 = double_div(5, 2) + print(result5) + + result6 = surplus(10, 5) + print(result6) + + result7 = add(2, 3) + print(result7) \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..3dc022a3 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,152 @@ +# 第二周-第一节 +## Python函数的基本介绍 +* 什么是函数? + + 函数就是一段定义的流程:输入数据,得到结果。在现实生活中,函数可以体现在方方面面。对厨师来讲,每一个菜谱都是函数;对农民来讲,每一种种菜的方法都是函数;对建筑工人来讲,每一个结构的修建都是函数;对司机来讲,在不同路线上的驾驶方式也是函数。 + + * 简单地说就是一个可以重复调用的代码片段。 + * 可以互相调用的代码片段 +* 函数的作用 + * 复用代码段 + +* **Python**中定义函数: + ```python + def foo(arg): + return "Hello" + str(arg) + ``` +* 函数组成 + * 参数 + * 必须参数 + + 参数必须**按顺序**传入 + * 关键字参数 + + 根据关键字参数传参可以不按顺序 + ```python + def foo(arg=None, args=None): + return "Hello" + str(arg) + ``` + * 默认参数 + ```python + def foo(arg='Super',args='Coding'): + return "Hello" + str(arg) + ``` + * 不定长参数 + > 在装饰器中会大量使用 + + 可以接受任意长度的参数 + + * **'*'** + 代表省略,打印参数为 **tuple** 元祖类型 + ```python + def foo(*args, **kwargs): + print(args) + print(kwargs) + return None + foo('Super', 'Coding', class_1='字典', class_2='字典2') + ('Super', 'Coding') + {'class_1': '字典', 'class_2': '字典2'} + ``` + * '**' + 两星号代表 dict字典类型参数 + ```python + def foo(*args, **kwargs): + print(args) + print(kwargs) + return None + foo('Super', 'Coding', class_1='字典', class_2='字典2') + ('Super', 'Coding') + {'class_1': '字典', 'class_2': '字典2'} + ``` + +* 返回值 + + 返回结果,默认返回 **None** + ```python + return None + ``` + 一个函数可以没有return 语句,可以有一个return 语句,也可以有多个return 语句 + + 一旦程序运行到return那么函数就会结束,return后面的代码永远不会被执行。 + +# Python运算符 +* 算术运算 + * `+` + * `-` + * `*`(乘法) + * `/`(除法) + * `//`(整除) + * `%`(取余) + * `**`(x的y次幂) + * `abs()`取绝对值 +* 赋值运算 + + 通过 = (等号) 赋值 + ```python + a = 1 + ``` +* 比较运算 + * `<` 小于 + * `>` 大于 + * `<=` 小于等于 + * `>=` 大于等于 + * `==` 等于 + * `!=` 不等于 + +* 标识号比较运算 + #### 比较两个变量的内存地址 + * `is` + * `is not` + * 赋值类型为 `str`,`int` 的时候需要考虑`python`的常量池 + ```python + a = 'a' + b = 'b' + a is b + >>> False + a = '你' + b = '好' + a is b + >>> True + ``` +* 成员检测运算 + + 判断元素是否在当前的序列中 + * `in` + ```python + a = [1,2,3] + 1 in a + >>> True + b = [1,2] + b in a + >>> False + ``` + * `not in` + +* 布尔运算 + + 判断当前语句的结果是`True`还是`False` + * `and` + + 只有两边都是`True`才返回`True` + + * `or` + + 两边表达式有一个是`True`返回的结果为`True` + * 短路 + ```python + 表达式A or 表达式B + 当表达式A为True时,表达式B就不会执行 + ``` + * `not` + + 逻辑取反 + +* 位运算 + + * `~` + * `^` + * `>>` + * `&` + * `|` + + -- Gitee From af97af7dec332448a9095a33fd9455f8f6bd9ff4 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 22 Dec 2020 22:27:40 +0800 Subject: [PATCH 02/27] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...2\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" index 3dc022a3..9c15debb 100644 --- "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -103,8 +103,8 @@ b = 'b' a is b >>> False - a = '你' - b = '好' + a = 123 + b = 123 a is b >>> True ``` -- Gitee From 641cbaf40c7eaf0b82b79ff2e374a1bcddde786f Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Wed, 23 Dec 2020 20:36:17 +0800 Subject: [PATCH 03/27] =?UTF-8?q?=E9=87=8D=E5=86=99=E5=BC=80=E6=96=B9?= =?UTF-8?q?=E8=BF=90=E7=AE=97=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4\344\270\200\350\212\202-\344\275\234\344\270\232.py" | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" index be8a0f24..bbe1c5cb 100644 --- "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" @@ -1,3 +1,5 @@ +import math + def add(a: int, b: int)-> int: """ 加法运算 @@ -34,11 +36,11 @@ def surplus(a:int, b:int)-> float: """ return a % b -def excract(a:int, b:int)-> None: +def excract(a:int): """ 开方运算 """ - return a**b + return math.sqrt(a) if __name__ == "__main__": @@ -60,5 +62,5 @@ if __name__ == "__main__": result6 = surplus(10, 5) print(result6) - result7 = add(2, 3) + result7 = excract(2) print(result7) \ No newline at end of file -- Gitee From e6cc2ac4cc33b40b6b378c01c095be4c707b6d12 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Thu, 24 Dec 2020 22:34:15 +0800 Subject: [PATCH 04/27] =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82-=E4=BD=9C=E4=B8=9A=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../week2/content.txt" | 17 ++ ...4\350\212\202-\344\275\234\344\270\232.py" | 97 ++++++ ...17\345\240\202\347\254\224\350\256\260.md" | 283 ++++++++++++++++++ 3 files changed, 397 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/content.txt" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/content.txt" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/content.txt" new file mode 100644 index 00000000..a9447d37 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/content.txt" @@ -0,0 +1,17 @@ + + def str_format(self): + # 字符串格式化 + str_format = '格式化' + format_result = 'format方法{}'.format(str_format) + + index_format = 'index format {0}'.format(str_format) + + args_format = 'args foramt {str_format}'.format(str_format=str_format) + + variable_foramt = f'变量方式{str_format}' + + num = 520.1314326 + num_format = '{:.4f}'.format(num) + + return format_result, index_format, args_format, variable_foramt, num_format + \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..091addf9 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,97 @@ +class Home_Work(object): + """ + 作业类 + """ + def decode_and_encode(self): + """ + 字符串的编码和解码 + """ + en_string = '字符串' + en_string = en_string.encode('utf-8') # 编码 + de_string = en_string.decode('utf-8') # 解码 + return en_string, de_string + + def str_crud(self): + """ + 字符串crud + """ + create_str = '字符串' + create_str += '创建' + + index_ = create_str[2] # 索引字符 + find_str = create_str.find('创') # 获取目标字符索引值 + + startswith_str = '开始字符' + print(startswith_str.startswith('开')) # True + + endswith = '结束字符' + print(endswith.endswith('符')) # True + + replace_str = '替换&字符' + replace_str = replace_str.replace('&', '') + split_str = '切割*字符' + split_str = split_str.split('*') + + join_str = ','.join(split_str) # 拼接 + + strip_str = ' 删除前后空格 ' + strip_str = strip_str.strip() + + return create_str, find_str, replace_str, split_str, strip_str, index_ + + def str_format(self): + """ + 字符串格式化 + """ + str_format = '格式化' + format_result = 'format方法{}'.format(str_format) + + index_format = 'index format {0}'.format(str_format) + + args_format = 'args foramt {str_format}'.format(str_format=str_format) + + variable_foramt = f'变量方式{str_format}' + + num = 520.1314326 + num_format = '{:.4f}'.format(num) + + return format_result, index_format, args_format, variable_foramt, num_format + + def save_content(self): + """ + 保存文件 + """ + f = open('week2/content.txt', 'w', encoding='utf-8') + content = """ + def str_format(self): + # 字符串格式化 + str_format = '格式化' + format_result = 'format方法{}'.format(str_format) + + index_format = 'index format {0}'.format(str_format) + + args_format = 'args foramt {str_format}'.format(str_format=str_format) + + variable_foramt = f'变量方式{str_format}' + + num = 520.1314326 + num_format = '{:.4f}'.format(num) + + return format_result, index_format, args_format, variable_foramt, num_format + """ + f.write(content) + f.close() + print('写入文件成功!') + + + + + + +if __name__ == "__main__": + hw = Home_Work() + hw.decode_and_encode() + hw.str_format() + hw.str_format() + hw.save_content() + diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..d084b5c1 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,283 @@ +# 第二周-第二节课 + +## 字符串(字符序列)和字节序列 + +- 字符 + + - 由于历史原因, 将字符定义为`unicode`字符还不够准确, 但是未来字符的定义一定是`unicode`字符 + +- 字节 + + 就是字符的二进制表现形式 + +- 码位 + + 我们计算机显示的实际上是码位 + + ``` + >>> '你好'.encode("unicode_escape").decode() + '\\u4f60\\u597d' + >>> + >>> '\u4f60\u597d' + '你好' + ``` + + - `unicode`标准中以4~6个十六进制数字表示 + +- 编码 + + - 字符序列(string) -> 字节序列(bytes) -------------编码(encode) + + ``` + >>> "你好".encode("utf-8") + b'\xe4\xbd\xa0\xe5\xa5\xbd' + ``` + + - 字节序列(bytes) -> 字符序列(string) -------------解码(decode) + + ``` + >>> b + b'\xe4\xbd\xa0\xe5\xa5\xbd' + >>> b.decode("utf") + '你好' + ``` + +- 编码错误 + + - 乱码和混合编码 + + - 检查编码 + + 没有办法通过字节序列来得出编码格式, 都是统计学来预估当前的编码 + + ``` + # 安装chardet + pip install chardet + + # 导入charet + >>> import chardet + >>> chardet.detect(b) + ``` + + - 解决乱码和混合编码 + + - 忽略错误编码 + + ``` + >>> b_2.decode("utf-8", errors='ignore') + '你好' + ``` + + - 利用鬼符来替换 + + ``` + >>> b_2.decode("utf-8", errors='replace') + '你好��' + ``` + + + +## 字符串的CRUD操作 + +``` +通过dir("")可以查看当前字符串的操作方法 +``` + +- Create(创建) + + - `+` + + ``` + >>> a = "a" + >>> id(a) + 22951584 + >>> a = a + "b" + >>> id(a) + 60513280 + >>> a + 'ab' + ``` + + - `+=` + + ``` + a += "b" 就是 a = a + "b" 省略写法 + ``` + +- Retrieve(检索) + + - 根据索引获取字符 + + 在计算机语言当中, 索引值是从0开始数的 + + ``` + >>> a = "hello, world" + >>> a[1] + 'e' + ``` + + - find和index(获取目标字符的索引值) + + ``` + >>> a.find("e") + 1 + >>> a.find("!") + -1 + + # 找不到目标字符时, index会报错 + >>> a.index("!") + Traceback (most recent call last): + File "", line 1, in + ValueError: substring not found + ``` + + - startswith和endswith + + ``` + >>> f = "2020-11-22-xxxxx" + >>> f.startswith("2020-11-22") + True + >>> f = "xxxxx.jpg" + >>> f.endswith("jpg") + True + ``` + +- UPDATE(更新) + + - replace(替换) + + 返回的是一个新的字符串 + + ``` + a.replace("wer", "wor") + ``` + + - split(分割) + + ``` + >>> a = "<>, <>, <>" + >>> a.split(",") + ['<>', ' <>', ' <>'] + ``` + + - join(拼接) + + ``` + >>> b + ['<>', ' <>', ' <>'] + >>> ",".join(b) + '<>, <>, <>' + ``` + +- DELETE(删除) + + - strip + + ``` + >>> a + ' hello, world ' + >>> a.strip() + 'hello, world' + >>> + + ``` + + - lstrip + + - rstrip + +## 字符串的输出和输入 + +- 保存到文件 + + ``` + # open函数打开一个文件, 没有文件会新建, 但是路劲不对会报错 + # 指定文件名, 方法(读, 写, 追加), 编码格式 + output = open("output.txt", "w", encoding="utf-8") + content = "hello, world" + # 正式写入文件 + output.write(content) + # 关闭文件句柄 + output.close() + ``` + +- 读取文件 + + ``` + input = open("output.txt", "r", encoding="utf-8") + # 获取文件中的内容 + content = input.read() + print(content) + + # 暂时理解为只能读取一遍 + content_2 = input.read() + print(content_2) + ``` + +- 追加文件 + + ``` + output = open("output.txt", "a", encoding="utf-8") + content = "\nhello, world" + # 正式写入文件 + output.write(content) + # 关闭文件句柄 + output.close() + ``` + +## 字符串的格式化输出 + +- format + + - 按传入参数默认顺序 + + ``` + a = "ping" + b = "pong" + + "play pingpong: {}, {}".format(a, b) + ``` + + - 按指定参数索引 + + ``` + a = "ping" + b = "pong" + + "play pingpong: {0}, {1}, {0}, {1}".format(a, b) + ``` + + - 按关键词参数 + + ``` + a = "ping" + b = "pong" + + print("play pingpong: {a}, {b}, {a}, {b}".format(a='ping', b='pong')) + ``` + + - 按变量(推荐, 但是只有3.6以上才可以使用) + + ``` + a = "ping" + b = "pong" + + print(f"playing pingpong: {a}, {b}") + ``` + + - 小数的表示 + + ``` + >>> "{:.2f}".format(3.14159) + '3.14' + >>> + ``` + +- % + + ``` + >>> "playing %s %s" % ("ping", "pong") + 'playing ping pong' + + ``` + -- Gitee From 5f33a8f3d23541da6ef8df12b263f043e372b8c9 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Fri, 25 Dec 2020 21:02:36 +0800 Subject: [PATCH 05/27] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=A9=BA=E6=A0=BC=20and=20=E7=B1=BB=E5=90=8D=E9=87=8D=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...14\350\212\202-\344\275\234\344\270\232.py" | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" index 091addf9..b9f3a58b 100644 --- "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" @@ -1,7 +1,8 @@ -class Home_Work(object): +class HomeWork(object): """ 作业类 """ + def decode_and_encode(self): """ 字符串的编码和解码 @@ -10,7 +11,7 @@ class Home_Work(object): en_string = en_string.encode('utf-8') # 编码 de_string = en_string.decode('utf-8') # 解码 return en_string, de_string - + def str_crud(self): """ 字符串crud @@ -38,7 +39,7 @@ class Home_Work(object): strip_str = strip_str.strip() return create_str, find_str, replace_str, split_str, strip_str, index_ - + def str_format(self): """ 字符串格式化 @@ -54,9 +55,9 @@ class Home_Work(object): num = 520.1314326 num_format = '{:.4f}'.format(num) - + return format_result, index_format, args_format, variable_foramt, num_format - + def save_content(self): """ 保存文件 @@ -83,15 +84,10 @@ class Home_Work(object): f.close() print('写入文件成功!') - - - - if __name__ == "__main__": - hw = Home_Work() + hw = HomeWork() hw.decode_and_encode() hw.str_format() hw.str_format() hw.save_content() - -- Gitee From 136513b9cc74348fc4d2f1e92b45f47dae249943 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sat, 26 Dec 2020 22:41:02 +0800 Subject: [PATCH 06/27] =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...1\350\212\202-\344\275\234\344\270\232.py" | 172 ++++++++ ...17\345\240\202\347\254\224\350\256\260.md" | 382 ++++++++++++++++++ 2 files changed, 554 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..22d0b6f0 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,172 @@ +# -*- coding: UTF-8 -*- +""" +@File :第二周-第三节-作业.py +@Author :Super +@Date :2020/12/26 +@Desc : +""" + + +class List(object): + """ + 列表操作类 + """ + List = ['default', 'list', 'value:'] + + @classmethod + def create(cls): + """ + 将元素添加到列表末尾 + """ + cls.List.append('name') + return cls.List + + @classmethod + def delete(cls): + """ + pop() 从列表末尾删除元素并返回删除的元素 + """ + pop_ele = cls.List.pop() + return pop_ele + + @classmethod + def select_sort(cls): + """ + 返回排序后的列表 + """ + cls.List.sort(reverse=True) + return cls.List + + @classmethod + def update(cls): + cls.List[2] = 'update_value' + return cls.List + + +class Dict(object): + """ + 字典操作类 + """ + Dict = {'default': 'value'} + + @classmethod + def create(cls): + """ + 新增字典元素 + """ + cls.Dict['name'] = 'Dict' + return cls.Dict + + @classmethod + def delete(cls): + """ + 删除字典元素并返回值 + """ + return cls.Dict.pop('name') + + @classmethod + def retrieve(cls): + """ + 查询键返回值,若键不存在则返回默认值None + """ + return cls.Dict.get('default', 'None') + + @classmethod + def update(cls): + """ + 更新字典值 + """ + cls.Dict['default'] = 'update_value' + return cls.Dict + + +class Tuple(object): + """ + 元祖操作类 + """ + Tuple = ('default', 'list', 'value:',) + + @classmethod + def create(cls): + """ + 元组创建 无方法 + """ + pass + + @classmethod + def delete(cls): + """ + 元祖元素删除 无方法 + """ + pass + + @classmethod + def retrieve(cls): + """ + 元祖索引取值,index,切片 + """ + index_0 = cls.Tuple[0] + setion = cls.Tuple[0:2] + return index_0, setion # 返回索引值为0的值, 返回0-2切片范围的值 + + @classmethod + def update(cls): + """ + 元祖更新 无方法 + """ + pass + + +class Set(object): + """ + 集合操作类 + """ + Set = {'default', 'value'} + + @classmethod + def create(cls): + """ + 新增集合元素 + """ + cls.Set.add('name') + return cls.Set + + @classmethod + def delete(cls): + """ + 删除集合元素 + """ + cls.Set.remove('value') + return cls.Set + + @classmethod + def retrieve(cls): + """ + 查询 元素 是否存在集合 + return True or False + """ + return 'default' in cls.Set + + @classmethod + def update(cls): + """ + 更新集合 + """ + new_set = cls.Set.union({'age', 'height'}) + return new_set + + +if __name__ == '__main__': + print('列表新增: ', List.create()) + print('列表删除: ', List.delete()) + print('列表排序: ', List.select_sort()) + print('列表更新: ', List.update()) + print('字典新增:', Dict.create()) + print('字典删除:', Dict.delete()) + print('字典检索:', Dict.retrieve()) + print('字典更新:', Dict.update()) + print('元祖检索:', Tuple.retrieve()) + print('集合新增:', Set.create()) + print('集合删除:', Set.delete()) + print('集合更新:', Set.update()) + print('集合检索:', Set.retrieve()) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..9283bf13 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week2/\347\254\254\344\272\214\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,382 @@ +# 第二周-第三节课 + +## 了解变量和引用 + +- 变量简单地说就是指向了一个实体 + +- 引用简单地说就是指向变量的变量 + + ``` + >>> a = 1 + >>> b = a + >>> id(a) + 1778508560 + >>> id(b) + 1778508560 + ``` + +## 基础数据结构的CRUD操作 + +- List(列表) + + **list中存的元素是引用** + + - create(增加) + + - append + + 末尾添加元素 + + ``` + >>> l = [] + >>> id(l) + 55200584 + >>> l.append("a") + >>> l + ['a'] + >>> id(l) + 55200584 + ``` + + - `+` 和`+=` + + - `+` + + 拼接两个列表, 然后返回一个新列表 + + - `+=` + + ``` + >>> l = ['a'] + >>> id(l) + 55200664 + >>> l += ['b'] + >>> id(l) + 55200664 + >>> l + ['a', 'b'] + ``` + + - `*`和`*=` + + ``` + >>> a = 'a' + >>> id(a) + 53622432 + >>> l = [a] * 10 + >>> l + ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] + >>> id(l[0]) + 53622432 + >>> id(l[1]) + 53622432 + >>> id(l[9]) + 53622432 + + # 赋值语句之后, a已经是一个新的对象了 + >>> a = 'b' + >>> l + ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] + >>> id(a) + 53647264 + ``` + + - insert + + 指定位置添加元素 + + ``` + l.insert(0, 'b') + ``` + + - Retrieve(检索) + + - 索引取值 + + 所有序列都支持索引取值 + + - 切片 + + ``` + your_list[start:end:step] + # 取一段区间 + your_list[start:end] + + # 取最后一个值 + your_list[-1] + + # 间隔问题 + your_list[1:20:2] + ``` + + - index + + ``` + >>> l + ['a', 'b', 'c'] + >>> l.index('a') + 0 + ``` + + - Update(更新) + + - 索引赋值 + + ``` + l[0] = 'a_1' + ``` + + - 切片赋值 + + ``` + >>> l + ['a_1', 'a_2', 'b', 'c'] + >>> l[0:2] = "a" + >>> l + ['a', 'b', 'c'] + >>> l[0:2] = 1 + ``` + + - DELETE(删除) + + - pop() + + 从末尾删除元素并返回 + + ``` + >>> l + ['a', 'b', 'c'] + >>> x = l.pop() + >>> l + ['a', 'b'] + >>> x + 'c' + ``` + + - clear() + + 清楚当前列表的元素, 不会改变列表的内存地址. + + - ★SORT(排序) + + - sort() + + ``` + >>> l + [1, 3, 2, 6, 4] + >>> l.sort() + >>> l + [1, 2, 3, 4, 6] + + ``` + + - sorted + + 排序后返回新列表 + + ``` + >>> l2 = sorted(l) + >>> l + [1, 3, 2, 6, 4] + >>> l2 + [1, 2, 3, 4, 6] + >>> id(l) + 55201384 + >>> id(l2) + 55200984 + ``` + + - reverse + + ``` + >>> l2 + [1, 2, 3, 4, 6] + >>> l2.reverse() + >>> l2 + [6, 4, 3, 2, 1] + ``` + + - reversed + + 倒序之后返回新列表 + + ``` + >>> l + [1, 3, 2, 6, 4] + >>> list(reversed(l)) + [4, 6, 2, 3, 1] + ``` + +- tuple + + - Create + + 无 + + - Retrieve + + - 索引取值 + - index + - 切片 + + - Update + + 无 + + - Delete + + 无 + +- dict + + - Create + + - 键对值赋值 + + - update + + 提供合并字典的功能 + + ``` + >>> d + {'a': 1} + >>> d2 = {"b":2, "c": 3} + >>> d.update(d2) + >>> d + {'a': 1, 'b': 2, 'c': 3} + ``` + + - setdefault + + 如果字典中没有当前key, 那么就设置默认值 + + ``` + >>> d + {'a': 1, 'b': 2, 'c': 3} + >>> d.setdefault('b', 0) + 2 + >>> d.setdefault('d', 0) + 0 + >>> d + {'a': 1, 'b': 2, 'c': 3, 'd': 0} + + ``` + + - Retrieve + + - 键对值访问 + + - get + + 键对值访问缺失key会报错, 而get可以指定默认值 + + ``` + >>> d['e'] + Traceback (most recent call last): + File "", line 1, in + KeyError: 'e' + >>> d.get('f') + >>> d.get('f', 0) + 0 + ``` + + - keys() + + 返回所有key + + ``` + d.keys() + ``` + + - values() + + 返回所有value + + ``` + d.values() + ``` + + - items() + + 返回所有键对值 + + ``` + d.items() + ``` + + - Update + + - 键对值赋值 + + ``` + d['a'] = 100 + ``` + + - update + + ``` + >>> d.update({"b": 200, "c": 300}) + >>> d + {'a': 100, 'b': 200, 'c': 300, 'd': 0} + ``` + + - Delete + + - pop(key) + + 删除当前元素并返回value + + - popitem() + + 对于人来说, 相当于随机返回一个item + + - clear() + +- set + + - Create + + - add + - update + + - Retrieve + + - 运算符`in` + + ``` + >>> s + {'a'} + >>> "a" in s + True + + ``` + + - update + + - union + + 合并两个set, 并返回一个新的set + + - delete + + - remove 和discard + + discard缺失元素时不会报错, 而remove会报错 + + ``` + >>> s + {'b', 'c', 'a'} + >>> s.remove("a") + >>> s + {'b', 'c'} + >>> s.discard("e") + >>> s.remove("a") + Traceback (most recent call last): + File "", line 1, in + KeyError: 'a' + >>> + ``` + + - pop() + + 当成无序删除并返回元素 \ No newline at end of file -- Gitee From e8b6c58e9d262e7d17c82e8e7e71531b96946f82 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 29 Dec 2020 22:01:07 +0800 Subject: [PATCH 07/27] =?UTF-8?q?=E7=AC=AC=E4=B8=89=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../week3/home_work.py" | 88 +++++++ ...0\350\212\202-\344\275\234\344\270\232.py" | 64 +++++ ...17\345\240\202\347\254\224\350\256\260.md" | 237 ++++++++++++++++++ 3 files changed, 389 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/home_work.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/home_work.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/home_work.py" new file mode 100644 index 00000000..ea385a05 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/home_work.py" @@ -0,0 +1,88 @@ +import math + + +class ParamsError(Exception): + pass + + +class HomeWork(): + def add(self, a: int, b: int) -> int: + """ + 加法运算 + """ + try: + return a + b + except ValueError as e: + raise ParamsError('参数异常') + finally: + pass + + def subtract(self, a: int, b: int) -> int: + """ + 减法运算 + """ + try: + return a - b + except ValueError as e: + raise ParamsError('参数异常') + finally: + pass + + def ride(self, a: int, b: int) -> int: + """ + 乘法运算 + """ + try: + return a * b + except ValueError as e: + raise ParamsError('参数异常') + finally: + pass + + def divide(self, a: int, b: int) -> float: + """ + 除法运算 + """ + try: + return a / b + except ValueError as e: + raise ParamsError('参数') + finally: + pass + + def double_div(self, a: int, b: int) -> int: + """ + 整除运算 + """ + try: + return a // b + except ValueError as e: + raise ParamsError('参数异常') + finally: + pass + + def surplus(self, a: int, b: int) -> float: + """ + 取余运算 + """ + try: + return a % b + except ValueError as e: + raise ParamsError('参数异常') + finally: + pass + + def excract(self, a: int): + """ + 开方运算 + """ + try: + return math.sqrt(a) + except ValueError as e: + raise ParamsError('参数异常') + finally: + pass + + +if __name__ == "__main__": + pass diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..fad44f2d --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,64 @@ +# -*- coding: UTF-8 -*- +""" +@File :第三周-第一节-作业.py +@Author :Super +@Date :2020/12/29 +@Desc : +""" +from home_work import HomeWork + + +def for_demo(): + """ + for 循环 计数 + 计算 1+2+3+4...+100的总和 + """ + sum = 0 + for i in range(1, 101): + sum += i + print(sum) + + +def while_demo(): + """ + while 循环 计数 + 计算 1+2+3+4...+100的总和 + """ + i = 1 + sum = 0 + while i <= 100: + sum += i + i += 1 + print(sum) + + +def fib_for(n): + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + yield a + + +def fib_while(n): + a, b = 0, 1 + while n > 0: + a, b = b, a + b + n -= 1 + yield a + + +if __name__ == '__main__': + for_demo() + while_demo() + for i in fib_for(10): + print(i, end=' ') + for i in fib_while(10): + print(i, end=' ') + hw = HomeWork() + print(hw.add(1,1)) + print(hw.divide(1,1)) + print(hw.double_div(1,1)) + print(hw.excract(1)) + print(hw.ride(1,1)) + print(hw.subtract(1,1)) + print(hw.surplus(1,1)) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..24715b74 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,237 @@ +# 第三周-第一节课 + +## Python的逻辑控制语句 + +- 条件判断语句 + + ![](https://ss.im5i.com/2020/12/26/-2.png) + - `if` + + - `elif` + + - `else` + + ``` + a = 50 + if a > 100: + print("a 超过阈值") + elif a == 50: + print("a 只有阈值的一半") + else: + print("a 小于阈值") + ``` + + + +- 循环语句 + + - `for` + + 遍历一个可迭代对象(暂时理解为list), 会影响相同作用域当中的变量 + + ``` + l = [1, 2, 3, 4, 5, 6] + e = 0 + + + for e in l: + print(e) + + print(f"final e value: {e}") + ``` + + - 获取索引值和值 + + ``` + l = [1, 2, 3, 4, 5, 6] + + + for i, e in enumerate(l): + print(f"index: {i}, value: {e}") + ``` + + - `while`循环 + + 一定要有逻辑判断语句来退出`while`循环 + + ``` + while 判断语句: + 表达式 + + while True: + 判断语句 + 表达式 + ``` + + - 跳出循环 + + - `break` + + 停止当前循环 + + - `continue` + + 跳过当前的执行逻辑, 立即执行下一个循环语句单元; + + - `pass` + + 跳过当前条件判断中的执行语句, 后续语句继续执行; + + + +## Python的异常与处理 + +- 异常 + + 程序遇到严重错误时, 会终止程序的运行并抛出异常 + + ``` + def my_sub(a, b): + return a / b + + my_sub(1, 0) + ``` + +- 捕获异常 + + ``` + try: + 表达式 + except [Exception] as e: + 表达式 + finnaly: + 表达式 + + + + def my_sub(a, b): + try: + return a / b + except ZeroDivisionError: + # print(e) + print("分母不可为0") + return None + finally: + print("function my_sub end") + + my_sub(1, 0) + ``` + + - Exception + + 所有异常的基类, 所有的异常都是Exception的子类 + + - 处理异常颗粒度要细一点, 尽量不要捕获基类Exception, 尤其是数据处理的时候. + + - 常见的异常 + + - IndexError + + 索引值超过了列表长度 + + ``` + >>> l = [1] + >>> l[2] + Traceback (most recent call last): + File "", line 1, in + IndexError: list index out of range + + ``` + + - KeyError + + 找不到Key + + ``` + >>> d = {"a": 1} + >>> d["b"] + Traceback (most recent call last): + File "", line 1, in + KeyError: 'b' + ``` + + - ValueError + + 传入的参数错误 + + ``` + >>> int('a1') + Traceback (most recent call last): + File "", line 1, in + ValueError: invalid literal for int() with base 10: 'a1' + + ``` + + - TypeError + + 类型错误, 常见于运算 + + ``` + >>> 1 + '2' + Traceback (most recent call last): + File "", line 1, in + TypeError: unsupported operand type(s) for +: 'int' and 'str' + + ``` + + - SyntaxError + + 语法报错, 检查自己的语法有没有写错 + + - IndentationError + + 缩进错误 + + - 混用tab和space(空格) + - 缩进长度不对 + +- 如何处理异常 + + - 处理 + + - 抛出新异常 + + ``` + def my_sub(a, b): + try: + return a / b + except ZeroDivisionError: + print("分母不可为0") + raise Exception("params error") + finally: + print("function my_sub end") + ``` + + - 重新抛出 + + ``` + def my_sub(a, b): + try: + return a / b + except ZeroDivisionError: + print("分母不可为0") + raise ZeroDivisionError + finally: + print("function my_sub end") + ``` + + - 忽略(不推荐) + + `pass` + + 用来指示当前处理语句没有正式写完, 尽量不要忽略异常, 否则代码的健壮度会很差, 造成不可预知的bug. + +- 自定义异常 + + ``` + class ParamsError(Exception): + pass + + def my_sub(a, b): + try: + return a / b + except ZeroDivisionError: + raise ParamsError("分母不可以为0") + finally: + print("function my_sub end") + ``` \ No newline at end of file -- Gitee From 97764fc1909e097c925968418b4829fe9e7469a7 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sat, 2 Jan 2021 11:50:26 +0800 Subject: [PATCH 08/27] =?UTF-8?q?=E7=AC=AC=E4=B8=89=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4\350\212\202-\344\275\234\344\270\232.py" | 44 +++ ...17\345\240\202\347\254\224\350\256\260.md" | 367 ++++++++++++++++++ 2 files changed, 411 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..fe6679cd --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,44 @@ +# -*- coding: UTF-8 -*- +""" +@File :第三周-第二节-作业.py.py +@Author :Super +@Date :2021/1/2 +@Desc : +""" +from pprint import pprint + +classes = [ + {"name": "n_1", "age": 24, "grade": "A"}, + {"name": "n_2", "age": 23, "grade": "B"}, + {"name": "n_3", "age": 28, "grade": "A"}, + {"name": "n_4", "age": 24, "grade": "A"}, + {"name": "n_5", "age": 25, "grade": "C"}, + {"name": "n_6", "age": 21, "grade": "D"}, + {"name": "n_7", "age": 27, "grade": "A"}, +] +classes.sort(key=lambda x: x['grade']) # 1. 根据 grade 排序 +pprint(classes) + +f = filter(lambda x: x['grade'] == 'A', classes) # 2. 筛选出 grade 为 A 的同学 +pprint(list(f)) + + +def age_add(a): + return a['age'] + 1 + + +c = map(age_add, classes) # 3. 将上述 age + 1 +pprint(list(c)) + + +def f(n): + """ + 使用递归重构斐波那契数列 + """ + if n <= 1: + return n + return f(n - 1) + f(n - 2) + + +for i in range(15): + print(f(i)) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..ee06a628 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,367 @@ +# 第三周-第二节课 + +## 重新认识函数 + +- 内置函数 + + - 认识Python自带的, 可全局调用的函数, 避免我们命名冲突导致了函数性状发生改变 + + - 查看Python携带的内置函数 + + ``` + from pprint import pprint + # 格式化输出的库 + pprint(dir(__builtins__)) + ``` + + - 常见的内置函数 + + - `str` + + ``` + >>> str(1.0) + '1.0' + ``` + + - `int` + + ``` + >>> int(1.0) + 1 + >>> int("1.0") + Traceback (most recent call last): + File "", line 1, in + ValueError: invalid literal for int() with base 10: '1.0' + >>> int("1") + 1 + >>> + ``` + + - `float` + + ``` + >>> float("1.0") + 1.0 + >>> float(1) + 1.0 + >>> float('1') + 1.0 + ``` + + - `bytes` + + ``` + >>> bytes('a'.encode("utf-8")) + b'a' + ``` + + - `bool` + + ``` + >>> bool(0) + False + >>> bool(1) + True + >>> bool(2) + True + >>> bool('0') ***** + True + >>> bool(0.0) + False + ``` + + - `list` + + 只要是序列都可以转换成`list` + + ``` + >>> list("qwe") + ['q', 'w', 'e'] + ``` + + - `tuple` + + ``` + >>> tuple("qwe") + ('q', 'w', 'e') + >>> tuple([1,2]) + (1, 2) + ``` + + - `dict` + + ``` + >>> dict(a=1) + {'a': 1} + ``` + + - `set` + + ``` + >>> set([1,2,2]) + {1, 2} + >>> set("qweqweqwe") **** + {'q', 'w', 'e'} + ``` + + - `id` + + 查看当前对象的内存地址 + + ``` + >>> a = "1" + >>> id(a) + 26114944 + ``` + + - `dir` + + - 当前对象下的所有方法和属性 + - 在Python中一切皆为对象 + + ``` + dir(__builtins__) + ``` + + - `max` + + 返回一个序列中的最大值 + + ``` + >>> max([2, 4,67,1]) + 67 + ``` + + - `min` + + 返回一个序列中的最小值 + + ``` + >>> min([2, 4,67,1]) + 1 + ``` + + - `range` + + 返回一组数字区间的可迭代对象 + + ``` + >>> r = range(100) + >>> r + range(0, 100) + + >>> for i in range(10): + ... print(i) + ``` + +- 函数的形参和实参 + + - 形参 + + 形式参数, 简单地说就是还没接受到实际值的参数. 函数未调用时就是形参 + + ``` + def my_power(a, b): + return a ** b + ``` + + - 实参 + + 实际传入的参数, 函数调用时传入的值就叫实参 + + ``` + print(my_power(2, 3)) + ``` + +- 函数的返回值 + + - 返回值的类型 + + 任意类型, 包括函数本身 + + - 如何接受返回值 + + - 接收单个值 + + - 一个变量接受返回的多个值 + + 实际上返回的是个`tuple` + + ``` + >>> def foo(a, b): + ... return a*2, b*2 + ... + >>> result = foo(1, 2) + >>> result + (2, 4) + ``` + + - 多个变量按顺序接收 + + 实现原理是**元组解包**(unpack) + + ``` + >>> a,b = foo(1,2) + >>> a + 2 + >>> b + 4 + # 等同于 + >>> result = foo(1,2) + >>> a, b = result + ``` + + - 不定长变量接收 + + ``` + >>> result + (1, 2, 3, 4, 5, 6, 7) + >>> a, *b, c = result + >>> a + 1 + >>> c + 7 + >>> b + [2, 3, 4, 5, 6] + ``` + +## 匿名函数 + +顾名思义匿名函数就是没有名字的函数, 一般都是提供给高阶函数调用. + +- 通过`lambda`关键字来声明匿名函数 + + ``` + >>> lambda x: x **2 + # 返回的是一个匿名函数对象 + at 0x018BB660> + ``` + +- 函数体是纯表达式 + + - 不能有复杂的逻辑判断语句 + + - 唯一例外的例子: + + ``` + lambda x: 返回值 if 纯表达式 else 返回值 + + lambda x: True if x % 2==0 else False + ``` + + + + - 不能有循环语句 + + - 不能有异常捕获 + + - 不能有赋值语句 + + - 不能有`return` + + - 默认表达式运行的结果就是返回值 + + ``` + >>> lambda x: x **2 + 返回值就是 x**2 + ``` + +- 例子 + + ``` + l = [[1,2], [2,1], [6,4], [3,5]] + l.sort(key=lambda x: x[1]) + print(l) + ``` + +## 高阶函数 + +接受函数作为参数, 或者把函数作为结果返回 + +- map(映射) + + 对一个序列每个元素进行相同的操作, 这个过程就叫映射 + + ``` + >>> l = [1,2,3] + >>> m = map(lambda x: x**2, [1,2,3]) + + # 获得返回结果是一个map对象 + >>> m + + >>> l + [1, 2, 3] + + # map对象是一个可迭代对象, 需要驱动可迭代对象返回值, list就有这样的功能. 暂时不要太纠结 + >>> list(m) + [1, 4, 9] + >>> l + [1, 2, 3] + ``` + + - 等同于以下: + + ``` + def my_powser_2(a): + return a ** 2 + + # 匿名函数只是图方便, 所有的匿名都可以通过正常函数替换 + >>> m = map(my_powser_2, [1,2,3]) + >>> list(m) + [1, 4, 9] + ``` + + - 多用于和`math`库进行运算操作 + + ``` + >>> m = map(math.sqrt, [1, 4, 9, 16, 25]) + >>> list(m) + [1.0, 2.0, 3.0, 4.0, 5.0] + ``` + + + +- filter(过滤) + + ``` + filter(函数, 可迭代对象) + 函数中的表达式返回结果为False, 就会被过滤 + ``` + + ``` + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + # 过滤偶数 + >>> f = filter(lambda x: x%2, l) + >>> list(f) + [1, 3, 5, 7, 9] + + # 过滤奇数 + >>> f = filter(lambda x: False if x%2 == 1 else True, l) + >>> list(f) + [0, 2, 4, 6, 8] + ``` + +## 递归函数 + +在函数中调用自身的函数就叫递归函数 + +- 核心思想 + + **将大的任务拆分为子任务来解决复杂问题**, 只要大任务能拆分成子任务, 就可以使用递归 + + ``` + F(n) = F(F(n-1)) + ``` + +- 声明一个递归函数(阶乘) + + - **一定要有退出机制** + + ``` + F(n) = n * F(n-1) + + def fact(n): + if n == 1: + return 1 + return n * fact(n-1) + ``` \ No newline at end of file -- Gitee From 7f6feedd177ac90dc3e3e528466abdb175b2da6d Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sun, 3 Jan 2021 12:48:24 +0800 Subject: [PATCH 09/27] =?UTF-8?q?=E7=AC=AC=E4=B8=89=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...1\350\212\202-\344\275\234\344\270\232.py" | 83 ++++++++++ ...17\345\240\202\347\254\224\350\256\260.md" | 155 ++++++++++++++++++ 2 files changed, 238 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..f8caf385 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,83 @@ +# -*- coding: UTF-8 -*- +""" +@File :第三周-第三节-作业.py +@Author :Super +@Date :2021/1/3 +@Desc :作用域与装饰器 +""" +from time import time + +variable = 6 + + +def local_fun() -> None: + """ + 将局部变量变成全局变量 + """ + global variable # 使用 global 关键字将局部变量变成全局变量 + variable = 66 + print(variable) + + +# local_fun() +# print(variable) + + +def enclosed_fun(): + """ + 将局部变量变成自由变量 + """ + total = 0 + count = 0 + + def fun(value): + nonlocal total, count # 使用 nonlocal 关键字将局部变量变成全局变量 + total += value + count += 1 + return total / count + + return fun + + +# avg = enclosed_fun() +# print(avg(1)) + + +# 输出函数执行时间装饰器 +def time_deco(fun): + def wrapper(*args, **kwargs): + start_time = time() + result = fun(*args, **kwargs) + end_time = time() + print(f"{fun.__name__} 执行时间:{format(end_time - start_time, '.2f')} 秒") + return result + + return wrapper + + +def cache_deco(fun): + """ + 为斐波那契数列添加缓存 + """ + cache = {} + + def wrapper(*args): + if args not in cache: + cache[args] = fun(*args) + return cache[args] + + return wrapper + + +@cache_deco +@time_deco +def f(n): + """ + 使用递归重构斐波那契数列 + """ + if n <= 1: + return 1 + return f(n - 1) + f(n - 2) + + +print(f(10)) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..a2cfe360 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week3/\347\254\254\344\270\211\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,155 @@ +# 第三周-第三节课 + +## 作用域 + +程序创建, 访问, 改变一个变量时, 都是在一个保存该变量的空间内进行, 这个空间被称为命名空间, 即作用域 + +- `Built-in` 内置 + + - 可以在Python环境中的任何模块, 任意位置访问和调用 + +- `Global` 全局变量 + + - 只作用于当前模块(可以理解为当前文件) + + - 可以简单地理解为定以在函数外的变量就是全局变量, 如果在函数体定义那就时局部变量. + + - 如何将局部变量变成全局变量? + + - 使用`global`关键字 + + ``` + a = 1 + + def foo(): + global a + a = 2 + print(a) + + foo() + print(a) + ``` + +- `Enclosed(嵌套)` 自由变量 + + 在嵌套函数中, 访问函数体之外的非全局变量 + + - 只作用于嵌套函数体 + + - 最大的应用就是闭包 + + - 自由变量是个相对的概念 + + - 将局部变量变成自由变量 + + - 使用`nonlocal`关键字 + + ``` + def make_averager(): + total = 0 + count = 0 + def averager(value): + nonlocal total, count + total += value + count += 1 + return total / count + return averager + + my_avg = make_averager() + print(my_avg(1)) + print(my_avg(2)) + ``` + + + +- `Local`局部变量 + + - 只作用于当前函数体 + + - **一旦变量在函数体中赋值**, 那么该变量相对该函数来说就是局部变量 + + ``` + a = 1 + b = [] + + + def foo(): + a = 2 + b.append(2) + # 局部变量会在函数声明的时候就定义好 + # 不是按照我们逻辑思维上先执行全局变量b.append(2), 然后再声明一个局部变量b + # 而是再函数声明之初就已经定义了b为局部变量 + # b = 3 + return None + + foo() + print(a) + print(b) + ``` + + + +## 闭包和装饰器 + +- 闭包 + + 闭包指延申了作用域的函数, 也就是作用域中的`Enclosed`的概念 + + ``` + def make_averager(): + series = [] + def averager(value): + series.append(value) + total = sum(series) + return total / len(series) + return averager + + # my_avg就是延申了作用域的函数 + # series就是被延申作用域的变量 + my_avg = make_averager() + print(my_avg(1)) + print(my_avg(2)) + ``` + +- 装饰器 + + - 实现原理 + + 就是闭包, 延申了被装饰函数的作用域, 本质是将函数作为参数传递给一个可调用对象(函数或类) + + - 目的 + + 增加和扩展可调用对象(函数或类)的行为 + + - 实现一个装饰器 + + - 通过`@`关键字装饰函数(Python 语法糖) + + ``` + def clock_it_deco(func): + def wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print(f"{func.__name__} execute time: {format(end_time - start_time, '.2f')} s") + return result + return wrapper + + # @other_deco + @clock_it_deco + def foo(a, b): + count = 1 + while True: + if count > a ** b: + break + count += 1 + + foo(10, 5) + ``` + + - 等同于 + + ``` + foo = clock_it_deco(foo) + foo(10, 5) + ``` \ No newline at end of file -- Gitee From 8c97f7fc519f7337e781d3791d446446c582d819 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 5 Jan 2021 21:47:21 +0800 Subject: [PATCH 10/27] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0\350\212\202-\344\275\234\344\270\232.py" | 40 +++++ ...17\345\240\202\347\254\224\350\256\260.md" | 151 ++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..e6458b03 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,40 @@ +# -*- coding: UTF-8 -*- +""" +@File :第四周-第一节-作业.py +@Author :Super +@Date :2021/1/5 +@Desc : +""" + +import datetime + +now = datetime.datetime.now() +time_stamp = now.timestamp() # 时间格式转换为时间戳 +print(time_stamp) + +format_time = now.strftime("%Y-%m-%d %H:%M:%S") # 时间格式转换为字符串格式 +print(format_time) + +now_time = '2021-01-05 21:29:54' +str_time = datetime.datetime.strptime(now_time, "%Y-%m-%d %H:%M:%S") # 字符串格式转换为时间格式 +print(str_time) + + +def get_date(day_delta: int = 0) -> str: + """如果传入的参数为 -1 就输出 年-月-日 格式日期 + 反之不传参数,就输出 年-月-日 时:分:秒 + :param day_delta: 标志(默认为0) + """ + if day_delta == -1: + now_time = datetime.datetime.today() + now = now_time.strftime("%Y-%m-%d") + return now + else: + now_time = datetime.datetime.today() + now = now_time.strftime("%Y-%m-%d %H:%M:%S") + return now + + +if __name__ == '__main__': + now = get_date() + now = get_date(day_delta=-1) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..d33a0b88 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,151 @@ +# 第四周-第一节课 + +## 导入第三方模块 + +- 导包的层级关系 + + - 模块(module) + + 以文件为载体, 包含各类对象 + + - 包(package) + + 以文件夹为载体, 包含了各类模块 + + - 库(lib) + + 包含了各类包 + +- `import 库` + +- `from 库/模块 import 模块/函数` + +- 导包的命名冲突 + + 通过`as`这个关键词来给当前模块/函数取个别名 + + ``` + from datetime import datetime as p_datetime + ``` + +## 时间模块time + +调用的都是系统级的接口, 提供时间的访问和转换的功能 + +- 查看时间 + + - 获取当前时间 + + ``` + # 有时区的 + time.localtime() + + 返回的是一个time.struct_time对象 + ``` + + - 时间戳 + + ``` + time.time() + ``` + + - 时间的格式化输出 + + ``` + now = time.localtime() + now = time.strftime("%Y-%m-%d %H:%M:%S", now) + print(now) + + # 可以省略时间对象 + now = time.strftime("%Y-%m-%d %H:%M:%S") + ``` + + - 运算 + + 将时间对象转换为`list`, 对相应的时间重新赋值后, 通过`time.struct_time`生成一个新的时间对象 + + ``` + time_list = list(time.localtime()) + time_list[2] = 4 + time.struct_time(time_list) + ``` + + - 时间休眠 + + 当前程序休眠n秒 + + ``` + time.sleep(3) + ``` + +## 时间模块datetime + +封装了time, 提供了更高级和更友好的接口 + +- 查看时间 + + ``` + # 获取计算机时间, 返回的是一个datetime.datime对象 + datetime.datetime.today() + + + # 获取指定时区的时间 + datetime.datetime.now(tz=None) + + # 获取utc时间 + datetime.datetime.utcnow() + ``` + +- 时间格式的转换 + + - `datetime.datetime` -> `str` + + ``` + now = datetime.datetime.now(tz=None) + now.strftime("%Y-%m-%d %H:%M:%S") + ``` + + - `str` -> `datetime.datetime` + + ``` + >>> now + '2021-01-03 23:38:26' + >>> datetime.datetime.strptime(now, "%Y-%m-%d %H:%M:%S") + datetime.datetime(2021, 1, 3, 23, 38, 26) + ``` + + - `datetime.datetime` -> `timestamp` + + ``` + >>> now + datetime.datetime(2021, 1, 3, 23, 40, 45, 749240) + >>> now.timestamp() + 1609688445.74924 + ``` + + - `timestamp` -> `datetime.datetime` + + ``` + >>> ts + 1609688445.74924 + >>> datetime.datetime.fromtimestamp(ts, tz=None) + datetime.datetime(2021, 1, 3, 23, 40, 45, 749240) + ``` + +- 时间运算 + + - `timedelta` + + 只作用于`datetime.datetime`格式 + + ``` + # 选中目标模块 ctrl+B / command+B 跳转到模块源码 + def __new__(cls, days=0, seconds=0, microseconds=0, + milliseconds=0, minutes=0, hours=0, weeks=0): + ``` + + ``` + >>> from datetime import timedelta + >>> now + timedelta(hours=-1) + datetime.datetime(2021, 1, 3, 22, 40, 45, 749240) + ``` \ No newline at end of file -- Gitee From c7a7fa65284ed87b68e2a2c52f16827b83f9f273 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 5 Jan 2021 22:31:13 +0800 Subject: [PATCH 11/27] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E9=94=99=E8=AF=AF=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4\270\200\350\212\202-\344\275\234\344\270\232.py" | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" index e6458b03..e6f86a18 100644 --- "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" @@ -7,6 +7,7 @@ """ import datetime +from datetime import timedelta now = datetime.datetime.now() time_stamp = now.timestamp() # 时间格式转换为时间戳 @@ -21,13 +22,14 @@ print(str_time) def get_date(day_delta: int = 0) -> str: - """如果传入的参数为 -1 就输出 年-月-日 格式日期 - 反之不传参数,就输出 年-月-日 时:分:秒 + """如果传入的参数为 -1 就输出 “前一天” 年-月-日 格式日期 + 反之不传参数,就输出 "当前" 年-月-日 时:分:秒 :param day_delta: 标志(默认为0) """ if day_delta == -1: now_time = datetime.datetime.today() - now = now_time.strftime("%Y-%m-%d") + reduce_days = now_time + timedelta(days=day_delta) + now = reduce_days.strftime("%Y-%m-%d") return now else: now_time = datetime.datetime.today() @@ -37,4 +39,5 @@ def get_date(day_delta: int = 0) -> str: if __name__ == '__main__': now = get_date() - now = get_date(day_delta=-1) + # now = get_date(day_delta=-1) + print(now) -- Gitee From c210856944e097556673394c3f701d4074ba84bd Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Thu, 7 Jan 2021 22:16:42 +0800 Subject: [PATCH 12/27] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82=20=E4=BD=9C=E4=B8=9A(=E7=B1=BB=E4=B8=8E?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=E4=B8=80)=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...6\345\257\271\350\261\241\344\270\200).py" | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\270\200).py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\270\200).py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\270\200).py" new file mode 100644 index 00000000..e3190dae --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\270\200).py" @@ -0,0 +1,86 @@ +# -*- coding: UTF-8 -*- +""" +@File :第四周-第二节-作业(类与对象一).py +@Author :Super +@Date :2021/1/7 +@Desc :类与对象(一) +""" +import math + + +class MyMath(object): + def add(self, a: int, b: int) -> int: + """ + 加法运算 + """ + return a + b + + def subtract(self, a: int, b: int) -> int: + """ + 减法运算 + """ + return a - b + + def ride(self, a: int, b: int) -> int: + """ + 乘法运算 + """ + return a * b + + def divide(self, a: int, b: int) -> float: + """ + 除法运算 + """ + return a / b + + def double_div(self, a: int, b: int) -> int: + """ + 整除运算 + """ + return a // b + + def surplus(self, a: int, b: int) -> float: + """ + 取余运算 + """ + return a % b + + def excract(self, a: int): + """ + 开方运算 + """ + return math.sqrt(a) + + +class MobilePhone(object): + def __init__(self, phone_name, color): + """ + 手机类 + :param phone_name: 手机品牌 + :param color: 手机颜色 + """ + self.phone_name = phone_name + self.color = color + + def send_message(self): + print(f"""【Python游戏】尊敬的Super,Python小游戏于10月24日全面开放, +3倍速升级,道具金币送不停快点叫上小伙伴一起来玩耍吧!退订回T + 发送端来自--{self.color}的{self.phone_name} + """) + + +class Computer(MobilePhone): + def __init__(self, phone_name, color): + super(Computer, self).__init__(phone_name=phone_name, color=color) + + def play_game(self): + print(f"打游戏,就用{self.color}的{self.phone_name}") + + +if __name__ == '__main__': + iPhone_11 = MobilePhone("苹果11", "白色") + iPhone_11.send_message() + android = MobilePhone("小米11", "烟紫色") + android.send_message() + computer = Computer("暗影精灵6", "暗黑色") + computer.play_game() -- Gitee From cd843d999f98c16128c98bada3b98158f8ec6170 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Fri, 8 Jan 2021 21:49:22 +0800 Subject: [PATCH 13/27] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A=20=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0\350\212\202-\344\275\234\344\270\232.py" | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" index e6f86a18..f84d2109 100644 --- "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232.py" @@ -22,22 +22,29 @@ print(str_time) def get_date(day_delta: int = 0) -> str: - """如果传入的参数为 -1 就输出 “前一天” 年-月-日 格式日期 - 反之不传参数,就输出 "当前" 年-月-日 时:分:秒 - :param day_delta: 标志(默认为0) + """如果传入是负数 就输出 “前几天” 年-月-日 格式日期 + 如果传入是正数 就输出 “后几天” 年-月-日 格式日期 + :param day_delta: """ - if day_delta == -1: + if str(day_delta).startswith('-'): + """ + 将传入参数转换为字符串再判断 是否已 - 开头 + 如果是 将日期向前减 + 否则 将日期向后加 + """ now_time = datetime.datetime.today() reduce_days = now_time + timedelta(days=day_delta) now = reduce_days.strftime("%Y-%m-%d") return now else: now_time = datetime.datetime.today() - now = now_time.strftime("%Y-%m-%d %H:%M:%S") + reduce_days = now_time + timedelta(days=+day_delta) + now = reduce_days.strftime("%Y-%m-%d") return now if __name__ == '__main__': - now = get_date() - # now = get_date(day_delta=-1) + # now = get_date() + now = get_date(day_delta=-1) + now = get_date(day_delta=4) print(now) -- Gitee From 045cd8e87a642db2d16deb62bc71392e966344ed Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sat, 9 Jan 2021 22:37:51 +0800 Subject: [PATCH 14/27] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E8=8A=82=20=E4=BD=9C=E4=B8=9A(=E7=B1=BB=E4=B8=8E?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=E4=BA=8C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...6\345\257\271\350\261\241\344\272\214).py" | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\272\214).py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\272\214).py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\272\214).py" new file mode 100644 index 00000000..bf0a227f --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week4/\347\254\254\345\233\233\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\347\261\273\344\270\216\345\257\271\350\261\241\344\272\214).py" @@ -0,0 +1,100 @@ +# -*- coding: UTF-8 -*- +""" +@File :第四周-第三节-作业(类与对象二).py +@Author :Super +@Date :2021/1/9 +@Desc :类与对象二 +""" + +import math + + +class MyMath(object): + + @staticmethod + def add(a: int, b: int) -> int: + """ + 加法运算 + """ + return a + b + + @staticmethod + def subtract(a: int, b: int) -> int: + """ + 减法运算 + """ + return a - b + + @staticmethod + def ride(a: int, b: int) -> int: + """ + 乘法运算 + """ + return a * b + + @staticmethod + def divide(a: int, b: int) -> float: + """ + 除法运算 + """ + return a / b + + @staticmethod + def double_div(a: int, b: int) -> int: + """ + 整除运算 + """ + return a // b + + @staticmethod + def surplus(a: int, b: int) -> float: + """ + 取余运算 + """ + return a % b + + @staticmethod + def excract(a: int): + """ + 开方运算 + """ + return math.sqrt(a) + + +class MobilePhone(object): + fast_charging = True # 类属性 + __parts = ["说明书", "充电器", "手机壳"] # 类私有属性 + + @classmethod + def get_parts(cls): + """ + 类方法,返回类的私有属性 + :return: + """ + return cls.__parts + + def __init__(self, phone_name, color, price): + """ + 手机类 + :param phone_name: 手机品牌 + :param color: 手机颜色 + """ + self.__price = price # 实例私有属性 + self.phone_name = phone_name + self.color = color + + def __str__(self): + return f'自定义输出格式:{self.__parts}' + + def send_message(self): + print(f"""【Python游戏】尊敬的Super,Python小游戏于10月24日全面开放, +3倍速升级,道具金币送不停快点叫上小伙伴一起来玩耍吧!退订回T + 发送端来自--{self.color}的{self.phone_name} + """) + + +if __name__ == '__main__': + # print(MyMath.add(1, 2)) + # print(MobilePhone.get_parts()) + m = MobilePhone("苹果11", "白色", 3000) + print(m) -- Gitee From 4f639212ccfb7cb34e54e9f6d64d994e74f69233 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 12 Jan 2021 23:29:27 +0800 Subject: [PATCH 15/27] =?UTF-8?q?=E7=AC=AC=E4=BA=94=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A(=E5=A4=9A=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E5=92=8C=E5=A4=9A=E8=BF=9B=E7=A8=8B)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...6\345\244\232\347\272\277\347\250\213).py" | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(\345\244\232\350\277\233\347\250\213\344\270\216\345\244\232\347\272\277\347\250\213).py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(\345\244\232\350\277\233\347\250\213\344\270\216\345\244\232\347\272\277\347\250\213).py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(\345\244\232\350\277\233\347\250\213\344\270\216\345\244\232\347\272\277\347\250\213).py" new file mode 100644 index 00000000..7740fd51 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(\345\244\232\350\277\233\347\250\213\344\270\216\345\244\232\347\272\277\347\250\213).py" @@ -0,0 +1,32 @@ +# -*- coding: UTF-8 -*- +""" +@File :第五周-第一节-作业(多进程与多线程).py +@Author :Super +@Date :2021/1/12 +@Desc :多进程与多线程 +""" +from threading import Thread +from multiprocessing import Process + + +def coding_music(index): + """ + :param index: 序号 + :return: None + """ + if index % 2 == 0: + print(f"我爱敲代码 {index}") + else: + print(f"一边敲代码一边听音乐 {index}") + + +if __name__ == '__main__': + + # for i in range(10): + # # 多线程版本 + # t1 = Thread(target=coding_music, args=(i,)) + # t1.start() + for i in range(10): + # 多进程版本 + t1 = Process(target=coding_music, args=(i,)) + t1.start() -- Gitee From 59edeb3000a2cca7c9339a9c82c9820d264989eb Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Thu, 14 Jan 2021 22:20:24 +0800 Subject: [PATCH 16/27] =?UTF-8?q?=E7=AC=AC=E4=BA=94=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82=20=E4=BD=9C=E4=B8=9A(=E8=BF=9B=E7=A8=8B?= =?UTF-8?q?=E5=92=8C=E7=BA=BF=E7=A8=8B=E9=97=B4=E9=80=9A=E4=BF=A1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../week5/logo.log" | 10 +++ ...3\351\227\264\351\200\232\344\277\241).py" | 83 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/logo.log" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\272\277\347\250\213\345\222\214\350\277\233\347\250\213\351\227\264\351\200\232\344\277\241).py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/logo.log" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/logo.log" new file mode 100644 index 00000000..a510c238 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/logo.log" @@ -0,0 +1,10 @@ +1 +5 +3 +0 +2 +4 +6 +7 +8 +9 diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\272\277\347\250\213\345\222\214\350\277\233\347\250\213\351\227\264\351\200\232\344\277\241).py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\272\277\347\250\213\345\222\214\350\277\233\347\250\213\351\227\264\351\200\232\344\277\241).py" new file mode 100644 index 00000000..f3e7f2b1 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(\347\272\277\347\250\213\345\222\214\350\277\233\347\250\213\351\227\264\351\200\232\344\277\241).py" @@ -0,0 +1,83 @@ +# -*- coding: UTF-8 -*- +""" +@File :第五周-第二节-作业(线程和进程间通信).py +@Author :Super +@Date :2021/1/14 +@Desc :线程和进程间通信 +""" +from multiprocessing import Process, Lock, Queue +from threading import Thread, Lock + + +def process_save_file(index, lock): + """ + 多进程锁 + :param index: 进程序号 + :param lock: 锁 + :return: None + """ + with lock: + with open('logo.log', 'a') as f: + f.write(str(index) + '\n') + + +zero = 0 +lock = Lock() + + +def thread_save_file(): + """ + 多线程锁 + :return: None + """ + global zero + for i in range(10 ** 5): + with lock: + zero += 1 + zero -= 1 + + +def save_to_queue(index, m_queue): + """ + 通过Queue实现进程通信 + :param index: + :param m_queue: + :return: + """ + m_queue.put(index) + + +if __name__ == '__main__': + process_list = [] + lock = Lock() + for i in range(10): + p = Process(target=process_save_file, args=(i, lock)) + process_list.append(p) + p.start() + + for p in process_list: + p.join() + print("完成!") + + # thread_list = [] + # for i in range(5): + # t = Thread(target=thread_save_file) + # thread_list.append(t) + # t.start() + # for t in thread_list: + # t.join() + # print("完成!") + # print(zero) + + # process_list = [] + # m_queue = Queue() + # for i in range(10): + # p = Process(target=save_to_queue, args=(i, m_queue)) + # process_list.append(p) + # p.start() + # + # for p in process_list: + # p.join() + # + # while True: + # print(m_queue.get()) -- Gitee From a5d6953710884299d3624508b599c939dfcbf9e7 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sun, 17 Jan 2021 20:50:55 +0800 Subject: [PATCH 17/27] =?UTF-8?q?=E7=AC=AC=E4=BA=94=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E8=8A=82=20=E4=BD=9C=E4=B8=9A(=E5=8D=8F=E7=A8=8B)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\344\270\232(\345\215\217\347\250\213).py" | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\345\215\217\347\250\213).py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\345\215\217\347\250\213).py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\345\215\217\347\250\213).py" new file mode 100644 index 00000000..ea91934d --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week5/\347\254\254\344\272\224\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(\345\215\217\347\250\213).py" @@ -0,0 +1,47 @@ +# -*- coding: UTF-8 -*- +""" +@File :第五周-第三节-作业(协程).py +@Author :Super +@Date :2021/1/17 +@Desc : +""" +import asyncio + + +class Response: + status_code = 200 + + +async def request_test(index): + print(f"当前请求序号: {index}") + response = Response() + await asyncio.sleep(1) + print(f"request 序号: {index}, response 相应状态码: {response.status_code}") + return response.status_code + + +def avg(): + total = 0 + len = 0 + while True: + total += yield + len += 1 + print("total = ", total, "n = ", len) + print("mean = ", total / len) + + +# x = avg() +# next(x) # 预激活,使其停留在第一个yield位置 +# while True: +# print("Please input number...") +# x.send(float(input())) + +loop = asyncio.get_event_loop() # 获取消息队列 +task_list = [] +for i in range(10): + task_list.append(request_test(i)) + +# 循环访问事件完成异步消息维护 +loop.run_until_complete(asyncio.wait(task_list)) + +loop.close() # 关闭事件循环 -- Gitee From 33b025e54840eb5e87808fc61aaee8d83ee13764 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sun, 24 Jan 2021 17:13:10 +0800 Subject: [PATCH 18/27] =?UTF-8?q?=E7=AC=AC=E5=85=AD=E5=91=A8-=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...17\345\240\202\347\254\224\350\256\260.md" | 162 ++++++++++++++++++ ...17\345\240\202\347\254\224\350\256\260.md" | 89 ++++++++++ ...17\345\240\202\347\254\224\350\256\260.md" | 82 +++++++++ 3 files changed, 333 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..081661da --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\200\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,162 @@ +# 第六周-第一节课 + +``` +推荐书籍 <<图解TCP/IP>> +``` + +## 输入网址后发生了什么 + +- 输入`url` + + 统一资源定位器`uniform resource locator` + + - `url`组成 + + ``` + https://www.baidu.com/ + 协议://域名[:端口]/路径 + + file:///H:/BaiduNetdiskDownload/ + ``` + + - `url`作用 + + 定位指定的资源. + + > url是uri的一个子集, uri是唯一标识符的意思. 身份证可以是uri, 但不是url. + +- DNS解析 + + 域名系统`Domain Name System`, 将域名解析为`IP`地址 + + - 域名解析流程 + + 域名(www.baidu.com) -> `DNS`服务器->返回真实的`IP`地址`36.152.44.96:443` -> 通过`IP`地址访问服务器 + +- 客户端与服务器建立连接. + + 客户端和服务端要互相确认身份, 建立连接通道后再发送数据 + +- 客户端正式向服务端发送请求. + +- 服务端处理请求并返回结果 + +- 浏览器接收到响应后, 做相应的渲染 + +## TCP/IP五层协议 + +``` +https://www.cnblogs.com/xjtu-lyh/p/12416763.html +``` + +![img](https://img2020.cnblogs.com/blog/1933084/202003/1933084-20200304223803915-1086885188.png) + +![img](https://img2020.cnblogs.com/blog/1933084/202003/1933084-20200304223816759-1375625683.png) + +![img](https://img2020.cnblogs.com/blog/1933084/202003/1933084-20200304223858705-1259511194.png) + +- 应用层 + + 为进程(客户端应用)和进程(服务器应用)之间提供服务. 应用层协议定义了应用之间进行数据交互的方式. + + ``` + 浏览网页 + 网易云 + 用python模拟请求 + ``` + + - 应用层协议 + - HTTP/HTTPS(超文本传输协议) + - DNS(域名系统) + - FTP(文件传输协议) + - SMTP(邮箱传输协议) + +- 传输层 + + 负责向两个主机应用进程的通信提供服务. + + > 一个主机可以开启不同的因看应用, 同不同的服务器之间进行通信, 但是都是共用一个传输服务来发送和接受信息 + + ``` + 进程 <---> 进程 + ``` + + - 传输层协议 + + - TCP(传输控制协议) + + 提供面向连接, (尽可能)可靠的数据传输服务. + + ``` + 一对一 + ``` + + ``` + 面向连接指的就是, 客户端和服务端进行三次交互验证, 也就是TCP三次握手. 建立连接后才可以发送数据. + ``` + + - 文件传输(FTP) + - 浏览网页(HTTP) + + - UDP(用户数据协议) + + 提供无连接的, 不保证数据传输的可靠性 + + ``` + 一对多, 一对一, 多对多... + ``` + + - 直播 + - 实况游戏 + +- 网络层 + + 决定了数据的转寄和**路径选择**, 封装和分组运输层产生的报文段/用户数据段. + + ``` + 主机 <---> 主机 + ``` + + - 网络层协议 + + - IP协议 + + - 公网IP + + 也就是指的传统IP地址, 是唯一的. + + - 局域网IP + + ``` + ipconfig + ``` + +- 数据链路层 + + 负责两台主机之间的数据传输, 向网路层提供数据传输服务 + + ``` + 网卡 <---> 网卡 + ``` + + - 数据链路层的作用 + + 比特流在传输媒介上传输时肯定有误差, 数据链路层的作用就是检错和纠错 + + - *流量控制 + - 差错检测 + - 差错控制 + +- 物理层 + + 物理层再局部局域网上传送数据帧, 在设备节点传输比特流. + + ``` + 光纤 <---> 光纤 + ``` + + - 物理层和数据链路层 + + ``` + 物理层才是真正传输数据的, 数据链路层是用来检查数据完整性的. + ``` \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..f44f64a7 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\270\211\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,89 @@ +# 第六周-第三节课 + +## 抓包 + +抓包其实就是中间人攻击, 只是我们会主动信任像fiddler这样的代理软件. + +对于服务端, 它伪装成客户端. 对于客户端, 它伪装成服务端. + +- 抓包软件 + + - Fiddler + + ``` + https://www.telerik.com/fiddler + ``` + + - Charles + + - wireshark + +- web端抓包 + + 现代互联网环境几乎都是https协议的网站 + + - 信任证书 + + ![Qi3lw.png](https://i.im5i.com/2021/01/23/Qi3lw.png) + + ``` + Rules -> Options -> HTTPS + - 勾选Decrypt HTTPS traffic + - 右上角点击Actions + - Trust Root Certificates + ``` + +- App端抓包 + + ``` + 下载夜神模拟器 + ``` + + - 打开远程终端连接 + + ![QinkU.png](https://i.im5i.com/2021/01/23/QinkU.png) + + ``` + Rules -> Options -> Connections -> Allow remote computes to connect + ``` + + - 把手机/模拟器的代理指向fiddler + + ``` + - wifi调出设置的时候要长按 + - 查看当前fiddler所在pc本地局域网ip + - ipconfig/ifconfig + - 在代理项中填写ip地址和fiddler端口, 默认是8888 + ``` + + - 信任证书 + + - App有一定的反爬措施, 第一件事就是修改请求协议 + + - 双向验证 + + 需要客户端也带上证书 + + - 解决请求协议上的反爬措施 + + - 安装VirtualXposed_0.18.2, JustTrustMe + +## 模拟请求 + +- PostMan简单使用 + + - GET + + - POST + + - form_data + + 参数表单 + + - x-www-form-urlencoded + + 如果headers中content-type为`x-www-form-urlencoded`, 那么我们需要在当前选项下填写参数 + + - raw + + 请求的真实body内容. \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 00000000..c554ca81 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week6/\347\254\254\345\205\255\345\221\250-\347\254\254\344\272\214\350\212\202-\351\232\217\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,82 @@ +# 第六周-第二节课 + +## 理解TCP/IP协议 + +- 什么是TCP/IP协议 + + `TCP/IP`并不是单个协议, 而是指一组协议的集合, 所以`TCP/IP`也叫`TCP/IP`协议族. + +- TCP/IP的作用 + + 起到了应用和硬件的之间承上启下的作用. + + ``` + 手机的APP应用 -> 路由器 -> 光猫 -> 运营商网络 -> 互联网 + ``` + +## TCP/IP三次握手 + +为了建立可靠的`TCP`连接, 尽可能地保证数据传输的正确性. + +![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019/7/%E4%B8%89%E6%AC%A1%E6%8F%A1%E6%89%8B.png) + +- 三次握手的过程 + + - 客户端向服务端发送带有`SYN(同步序列编号)`标识的数据包 --------------------------服务端确认了客户端的发送能力正常 + - 服务端向客户端发送了带有`SYN-ACK(确认字符)`标识的数据包-----------------------服务端确认了自己接受能力是正常 + - 客户端向服务端返回带有`ACK`标识的数据包-----------------------------------------------服务端确认了自己发送能力, 客户端接受正常 + +- 第2次握手已经传回了`ACK`, 为什么服务端还要返回`SYN`? + + 为了告诉客户端, 接收到的信号确实是其发送的信号, 表明了客户端到服务端的通信是正常的. + +## TCP/IP四次挥手 + +![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019/7/TCP%E5%9B%9B%E6%AC%A1%E6%8C%A5%E6%89%8B.png) + +- 四次挥手的过程 + + ``` + 我们以客户端作为主动关闭方来描述四次挥手过程 + ``` + + - 客户端向服务端发送了一个`FIN(finish)`数据包-------------------------------------关闭客户端到服务端的连接通道 + - 服务端收到`FIN`后, 返回了`ACK`数据包----------------------------------------------------服务端已经知道了客户端到服务端的连接通道已关闭 + - 服务端发送`FIN`数据包至客户端, 关闭与客户端的连接------------------------------目的是关闭服务端到客户端的连接通道 + - 客户端返回`ACK`数据包确认------------------------------------------------------------------通知服务端客户端已经知道了服务端到客户端之间的连接通道已关闭 + +## HTTPS + +![](https://pic3.zhimg.com/v2-f0ed37591ced473aaf5b18c1a3e41696_b.jpg) + +- https加密的过程 + - 客户端向服务端发送通信请求 + + - 服务端返回给客户端证书和密钥 + + - 客户端通过CA中心验证证书的真实性 + + - 客户端完成认证之后, 使用公钥对发送数据进行加密, 发送给服务端. + + - 非对称加密 + + ``` + 16 = 2* 8 也可以是 4 * 4 + 公钥就是拿到了16这个结果 + 私钥就是某个因数2 + 通过这样的方式才可以得出唯一解8 + ``` + + - 服务端收到加密后的请求数据后, 使用私钥进行解密. + + - 服务器和客户端使用**对称加密**进行通信 + +- 中间人攻击 + + ![](https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1091151144,717507179&fm=26&gp=0.jpg) + + 插入到客户端和服务端之间的通信, 对服务端伪造客户都安, 对客户端伪造服务端, 拦截通信产生的数据. + + - 产生的条件 + + 我们的客户端要主动信任中间人的证书 \ No newline at end of file -- Gitee From 3add0b9ba47b763b0da38260137f7db277ac5030 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 26 Jan 2021 23:00:28 +0800 Subject: [PATCH 19/27] =?UTF-8?q?=E7=AC=AC=E4=B8=83=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A(Mysql=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...6\345\272\223-\347\254\224\350\256\260.md" | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\200\350\212\202-mysql\346\225\260\346\215\256\345\272\223-\347\254\224\350\256\260.md" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\200\350\212\202-mysql\346\225\260\346\215\256\345\272\223-\347\254\224\350\256\260.md" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\200\350\212\202-mysql\346\225\260\346\215\256\345\272\223-\347\254\224\350\256\260.md" new file mode 100644 index 00000000..9dfe0ead --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\200\350\212\202-mysql\346\225\260\346\215\256\345\272\223-\347\254\224\350\256\260.md" @@ -0,0 +1,164 @@ +# 第七周-第一节课 + +## 数据库的基本介绍 + +- 关系型数据库 + + 创建在**关系模型基础上**的数据库, 用来存储和管理结构化的数据. + + - 关系模型 + + ``` + 类似python中类 + class Student: + def __init__(self, name, classes ...): + self.name = name + self.classes = classes + + def borrow(self, book): + print(f"student {self.name} borrow {book.name}") + + class Book: + pass + ``` + + > 在关系型数据库当中, 可以用三张数据表来表示 + > + > 1. 学生表 + > 2. 图书表 + > 3. 借阅表(记录行为) + + ![QmLj4.jpg](https://i.im5i.com/2021/01/24/QmLj4.jpg) + + - 关系型数据库的特点(也就是事务的特点) + + - ACID + + - Atomic(原子性) + + 指事务的操作是不可分割的, 要么完成, 要么不完成. 不存在其他的中间态 + + ``` + A -> B 转账, 如果中途中断, 那么整个银行系统就会崩溃. + ``` + + - Consistence(一致性) + + 事务A和事务B同时运行, 无论谁先结束, 数据库都会到达一致. + + ``` + 集合点在东方明珠, 同学A从静安出发, 同学B从黄埔出发. + 一致性不关心A和B谁先到达, 只关心最终两者都在东方明珠汇合. + ``` + + - Isolation(隔离性) + + 解决多个事务**同时**对数据进行读写和修改的能力. + + - Duration(持久性) + + 当某个事务一旦提交, 无论数据库崩溃还是其他原因, 该事务的结果都能够被持久化地保存下来. + + ``` + 事务的所有操作都是有记录的, 即使数据库中途崩溃, 仍然可以通过记录恢复 + ``` + + - 适用场景 + + 考虑到事务和日志 + + - 对数据完整性有要求. + + - 存储的数据结构化完整. + + - **单个**数据库服务实例可以满足需求. + + > 建立集群方案, 大多需要适用企业版, 企业版收费高昂. + + - 读表操作远远大于写表操作. + +- 非关系型数据库(`Nosql, not noly sql`) + + 创建在`Nosql`系统存储(键对值)基础上的数据库, 既可以存储结构化的数据, 也可以存储非结构化的数据. + +## Mysql数据库的基本使用 + +- 连接 + + - localhost + + > 填写主机的时候就是填写ip地址 + + localhost对应的地址约等于`127.0.0.1` + +- 数据库(database) + + - Create + + ``` + create database tunan_class_2; + ``` + + - 设置字符集 + + - `utf8`和`utf8mb4` + + `mysql`中`utf8`字符是不全的, `utf8mb4`才是和我们python中的`utf-8`字符集一致. + + - 排序规则 + + 选择默认的`utf8mb4_general_ci` + + - Retrieve + + ``` + show databases; + ``` + + - Update + + ``` + ALTER database tunan_class_2 DEFAULT CHARACTER SET 'utf8mb4' + ``` + + - Delete + + ``` + drop database 库名 + ``` + +- 数据表(table) + + - Create + + ``` + use tunan_class; + CREATE TABLE class_2( + id int PRIMARY KEY auto_increment, + student_name varchar(255) + )DEFAULT charset=utf8mb4; + ``` + + - Retrieve + + ``` + show tables; + ``` + + - Update + + ``` + ALTER TABLE class_2 RENAME class_3; + ``` + + - Delete + + ``` + drop table 表名 + ``` + + - 只删除数据, 不删除表 + + ``` + truncate 表名 + ``` \ No newline at end of file -- Gitee From a3a9e908cb89590c29b5147dc00ba2ec9f5cc8cc Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Thu, 28 Jan 2021 22:20:58 +0800 Subject: [PATCH 20/27] =?UTF-8?q?=E7=AC=AC=E4=B8=83=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82=20=E4=BD=9C=E4=B8=9A(Mysql=E4=BA=8C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\345\237\272\347\241\200\344\272\214).sql" | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\272\214).sql" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\272\214).sql" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\272\214).sql" new file mode 100644 index 00000000..8999ba48 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\272\214).sql" @@ -0,0 +1,49 @@ +/* + Navicat Premium Data Transfer + + Source Server : mysql + Source Server Type : MySQL + Source Server Version : 80019 + Source Host : localhost:3306 + Source Schema : homework_db + + Target Server Type : MySQL + Target Server Version : 80019 + File Encoding : 65001 + + Date: 28/01/2021 22:18:31 +*/ + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for class_type +-- ---------------------------- +DROP TABLE IF EXISTS `class_type`; +CREATE TABLE `class_type` ( + `int_field` int(0) NULL DEFAULT NULL, + `bigint_field` binary(19) NULL DEFAULT NULL, + `float_field` float(7, 0) NULL DEFAULT NULL, + `double_field` double(15, 0) NULL DEFAULT NULL, + `decimal_field` decimal(65, 0) NULL DEFAULT NULL, + `datetime_field` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of class_type +-- ---------------------------- +INSERT INTO `class_type` VALUES (1234567890, 0x31323334353637383930313233343536372E39, 123, 123123123123123, 34523512312432534534534234, '2021-01-28 22:08:53'); + +SET FOREIGN_KEY_CHECKS = 1; + + +INSERT INTO class_type(int_field, bigint_field, float_field, double_field, decimal_field) VALUE(1234567890, 12345678901234567.9, 123.1231231, 123123123123123, 34523512312432534534534234); + + +SELECT 52 + 100; +SELECT 100 - 50; +SELECT 50 * 50; + +SELECT SUM(int_field * 0.1) as sum_ , AVG(bigint_field) as biging_ +FROM class_type -- Gitee From 82c501bc160d265ac00e39f5a5779fe5ddb0b71f Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sun, 31 Jan 2021 12:27:53 +0800 Subject: [PATCH 21/27] =?UTF-8?q?=E7=AC=AC=E4=B8=83=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E8=8A=82=20=E4=BD=9C=E4=B8=9A(Mysql=E4=B8=89)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\345\237\272\347\241\200\344\270\211).sql" | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\270\211).sql" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\270\211).sql" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\270\211).sql" new file mode 100644 index 00000000..16ea6986 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week7/\347\254\254\344\270\203\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\237\272\347\241\200\344\270\211).sql" @@ -0,0 +1,58 @@ +-- INSERT INTO person(Id, Email) VALUES(4, 'b@e.com') 单条插入 +-- INSERT INTO person(Id, Email) VALUES(4, 'b@e.com'), (5, 'e@b.com'), (6, 'f@e.com') 多条插入 + +-- SELECT * FROM `person` -- 查询所有记录 + +-- SELECT * FROM `employee` WHERE name = 'Joe' AND ManagerId = 3 -- 条件查询 + +-- SELECT * FROM `actor` WHERE first_name LIKE '%m%' -- 模糊查询 + +-- SELECT * FROM `actor` LIMIT 100 -- 限制返回数量 + +-- SELECT DISTINCT film_id FROM `inventory` -- 过滤重复值 + +-- SELECT * FROM `city` ORDER BY city ASC -- 升序 +-- SELECT * FROM `city` ORDER BY city DESC -- 降序 + +-- SELECT count(*) FROM `city` -- 获取查询结果数量 + +-- UPDATE `person` SET Email='123@qq.com' WHERE id=6 -- 更新表字段值 + +-- DELETE FROM `person` WHERE id = 2 -- 删除记录 + +-- 并集 +SELECT name from class_1 WHERE name is not NULL +UNION +SELECT name from class_2 WHERE name is not NULL + +-- 交集 +SELECT s1.name FROM +(SELECT name from class_1 WHERE name is not NULL) as s1 +JOIN +(SELECT name from class_2 WHERE name is not NULL) as s2 +ON s1.name=s2.name + +-- 差集 +SELECT * FROM // s1对s2的差集, select就可以使用s1.name +(SELECT name from class_1 WHERE name is not NULL) as s1 +LEFT JOIN +(SELECT name from class_2 WHERE name is not NULL) as s2 +ON s1.name=s2.name +WHERE s2.name is NULL // 限定s1有, s2没有的记录 + +-- 补集 +SELECT s1.name FROM +(SELECT name from class_1 WHERE name is not NULL) as s1 +LEFT JOIN +(SELECT name from class_2 WHERE name is not NULL) as s2 +ON s1.name=s2.name +WHERE s2.name is NULL + +UNION + +SELECT s2.name FROM +(SELECT name from class_1 WHERE name is not NULL) as s1 +RIGHT JOIN +(SELECT name from class_2 WHERE name is not NULL) as s2 +ON s1.name=s2.name +WHERE s1.name is NULL \ No newline at end of file -- Gitee From 63c05fd020a139c946c40cf4406f3761395899a4 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Tue, 2 Feb 2021 22:41:01 +0800 Subject: [PATCH 22/27] =?UTF-8?q?=E7=AC=AC=E5=85=AB=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A(Mysql=E5=9B=9B)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...75\234\344\270\232(mysql\345\233\233).sql" | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(mysql\345\233\233).sql" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(mysql\345\233\233).sql" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(mysql\345\233\233).sql" new file mode 100644 index 00000000..330fe151 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\200\350\212\202-\344\275\234\344\270\232(mysql\345\233\233).sql" @@ -0,0 +1,43 @@ +/* + Navicat Premium Data Transfer + + Source Server : mysql + Source Server Type : MySQL + Source Server Version : 80019 + Source Host : localhost:3306 + Source Schema : world + + Target Server Type : MySQL + Target Server Version : 80019 + File Encoding : 65001 + + Date: 02/02/2021 22:34:41 +*/ + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for countrylanguage +-- ---------------------------- +DROP TABLE IF EXISTS `countrylanguage`; +CREATE TABLE `countrylanguage` ( + `CountryCode` char(3) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `Language` char(30) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `IsOfficial` enum('T','F') CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'F', + `Percentage` float(4, 1) NOT NULL DEFAULT 0.0, + PRIMARY KEY (`CountryCode`, `Language`) USING BTREE, + INDEX `CountryCode`(`CountryCode`) USING BTREE, + CONSTRAINT `countryLanguage_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES `country` (`Code`) ON DELETE RESTRICT ON UPDATE RESTRICT +) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic; + +SET FOREIGN_KEY_CHECKS = 1; + + +SELECT COUNT(*) as 总记录数, +FORMAT(AVG(Percentage),2) as 平均数, +SUM(Percentage) as 总数, +MAX(Percentage) as 最大值, +MIN(Percentage) as 最小值, +IsOfficial as 是否官方 +FROM countrylanguage GROUP BY IsOfficial \ No newline at end of file -- Gitee From 8368a426e38bc2c1b3f8cf32750c725d1e8a3ca5 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Fri, 5 Feb 2021 21:32:24 +0800 Subject: [PATCH 23/27] =?UTF-8?q?=E7=AC=AC=E5=85=AB=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82=20=E4=BD=9C=E4=B8=9A(Mysql=E4=BA=94)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...75\234\344\270\232(mysql\344\272\224).sql" | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\344\272\224).sql" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\344\272\224).sql" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\344\272\224).sql" new file mode 100644 index 00000000..757caa9d --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232(mysql\344\272\224).sql" @@ -0,0 +1,27 @@ +-- SELECT * FROM `employee` + +-- 创建存储过程 +CREATE PROCEDURE select_emp(locl_name VARCHAR(20)) +BEGIN + SELECT * + FROM employee + WHERE Name=locl_name; +END + +CALL select_emp('Joe'); -- 调用存储过程 + +drop PROCEDURE select_emp; -- 删除存储过程 + +-- 创建触发器 +CREATE TRIGGER check_name +BEFORE INSERT +ON employee +FOR EACH ROW +BEGIN + IF new.`Name` NOT IN ("HaHa", "HeiHei") THEN + SET new.`Name`='不符合条件'; + END IF; +END +USE sakila; +SHOW TRIGGER FROM sakila; -- 查看触发器 +DROP TRIGGER check_name; -- 删除触发器 -- Gitee From f16bc9e3e13ed810f768189cc810ab5de9442014 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sun, 7 Feb 2021 17:16:27 +0800 Subject: [PATCH 24/27] =?UTF-8?q?=E7=AC=AC=E5=85=AB=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E8=8A=82=20=E4=BD=9C=E4=B8=9A(Mysql=E5=85=AD)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...275\234\344\270\232(mysql\345\205\255).py" | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\205\255).py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\205\255).py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\205\255).py" new file mode 100644 index 00000000..8b215e00 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week8/\347\254\254\345\205\253\345\221\250-\347\254\254\344\270\211\350\212\202-\344\275\234\344\270\232(mysql\345\205\255).py" @@ -0,0 +1,91 @@ +# -*- coding: UTF-8 -*- +""" +@File :第八周-第三节-作业(mysql六).py +@Author :Super +@Date :2021/2/7 +@Desc : +""" +import pymysql +import random +import time + +MYSQL_CONF = { + "host": "127.0.0.1", + "user": "root", + "password": "123456", + "db": "sakila" +} + +mysql_con = pymysql.connect(**MYSQL_CONF) # 连接数据库 +cur = mysql_con.cursor() # 获取游标 + + +def insert_one(): + """ + 插入单条记录 + :return: + """ + for i in range(10): + name = f"Super_{i}" + salary = format(random.uniform(10000, 20000), ".2f") + sql = "INSERT INTO `employee`(`Name`, `Salary`) VALUES ('%s', '%s')" % (name, salary) + print(sql) + cur.execute(sql) + mysql_con.commit() + + +def insert_many(): + """ + 插入多条记录 + :return: + """ + data_list = [] + for i in range(20): + name = f"Super_{i}" + salary = format(random.uniform(10000, 20000), ".2f") + data_list.append((name, salary)) + + sql = """INSERT INTO employee(Name, Salary) VALUES (%s, %s)""" + print(data_list) + cur.executemany(sql, data_list) + mysql_con.commit() + + +def get_return(): + """ + 查询返回数据 + :return: + """ + sql = "SELECT * FROM employee" + cur.execute(sql) + results = cur.fetchall() + print(results) + +def transaction(): + """ + 事物提交、回滚 + :return: + """ + try: + sql = "DELETE FROM employee where Name='Super_0'" + cur.execute(sql) + sql_2 = "INSERT INTO employee VALUES(name)" + cur.execute(sql_2) + except Exception as e: + print(e.args) + print("rollback") + mysql_con.rollback() + finally: + mysql_con.commit() + +""" +CREATE INDEX city_name_index ON city(city) -- 创建索引 +SHOW INDEX FROM city -- 查看索引 +ALTER TABLE city DROP INDEX city_name_index -- 删除索引 +""" + +if __name__ == '__main__': + # insert_one() + # insert_many() + # get_return() + transaction() \ No newline at end of file -- Gitee From 2610be2cf02738df9ee816859a17dcd18925f830 Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Wed, 24 Feb 2021 21:15:04 +0800 Subject: [PATCH 25/27] =?UTF-8?q?=E7=AC=AC=E4=B9=9D=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=20=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../week9/detail_jd.html" | 3996 +++++++++++++ .../week9/search_jd.html" | 5284 +++++++++++++++++ ...5\345\221\250-\344\275\234\344\270\232.py" | 45 + 3 files changed, 9325 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/detail_jd.html" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/search_jd.html" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\344\275\234\344\270\232.py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/detail_jd.html" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/detail_jd.html" new file mode 100644 index 00000000..784d707c --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/detail_jd.html" @@ -0,0 +1,3996 @@ + + + + + + 【小米Redmi Note9 Pro】Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米【行情 报价 价格 评测】-京东 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + +
+
+
+ + + +
+
+ +
+
+
+ +
+ +
+
+
+
+ +
+
    +
    + + + +
    +
    +
    +
    + + > + 我的购物车 +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    >
    + +
    >
    + +
    >
    + +
    >
    +
    小米Redmi Note9 Pro
    +
    +
    +
    + + 自营 + +
    +
    + +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    客服
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    + 关注微店 +

    关注微店

    +
    +
    +
    +

    手机下单

    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
      +
    • + +
    • +
    + Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米 + +
    +
    + +
    +
    + +
    + +
    + + +
    +
      +
    • Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
    • +
    • Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
    • +
    • Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
    • +
    • Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
    • +
    • Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
    • +
    +
    +
    + +
    +
    +
    +
    + 当季新品 + Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
    +
    +
    +
    +
    + +
    +
    +
    +
    京 东 价
    +
    + + + + + 降价通知 +
    + + + + fans + +
    + + + + + + + + + + +
    +
    + + + +
    +
    +

    累计评价

    + 0 +
    +
    +
    +
    +
    +
    促  销
    +
    +
    + + + + + + + + + + +
    + 展开促销 + +
    +
    +
    +
    +
    +
    +
    + +
    + +
    +
    增值业务
    +
    +
      +
    +
    +
    +
    +
    配 送 至
    +
    +
    +
    +
    +
    +
    --请选择--
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    支持
    +
    +
      + +
      +
      +
      +
      +
      +
      + + + + +
      + +
      +
      +
      选择颜色
      + +
      +
      +
      选择版本
      + +
      +
      +
      购买方式
      + +
      + +
      + + + + + + + + + + + +
      + +
      +
      本地活动
      +
      +
        +
        +
        + +
        +
        +
        +
        + + +
        +
        +
        +

        为你推荐

        +
        +
        +
        +
        +
        + +
        + +
        +
        +
        + +
        +
        +
        +
          +
        • 人气配件
        • +
        +
        +
        +
        + +
        +
        +
        + + +
        +
        +
          +
          +
          +
          + +
          +
          已选择0个配件
          +
          + 组合价 + ¥暂无报价 +
          + + 配件选购中心 + = +
          +
          +
          +
          +
          +
          +
          +
            +
          • 店长推荐
          • +
          +
          +
          +
          +
          +
          +
          +
          + +
          +
          + +
          + +
          +
          +
          +

          手机热销榜

          +
          +
          +
          +
          +
            +
          • 同价位
          • +
          • 同品牌
          • +
          • 总排行
          • +
          +
          +
          +
          + +
          +
          +
          +
          + +
          +
          +
          +
          +
          +
          +
          + +
          +
          +
          +
          +
          +
          +
            +
          • 商品介绍
          • +
          • 规格与包装
          • +
          • 质检报告
          • +
          • 售后保障
          • +
          • 商品评价
          • +
          • + 手机社区
          • +
          • 京东试用new
          • +
          +
          +
          +
          +
          + +
          +
          +
          + +
          +
          +
          Redmi Note 9 Pro 5G 一亿像素 骁龙750G 33W快充 120Hz刷新率 静默星空 8GB+256GB 游戏智能手机 小米 红米
          +
          + X +
          +
          +
          +
          +
          +
          +
          +
          +
          +
          +
          +
          +
            +
          + +
            +
          • 商品名称:小米Redmi Note9 Pro
          • +
          • 商品编号:100016799388
          • +
          • 商品毛重:500.00g
          • +
          • 商品产地:中国大陆
          • +
          • CPU型号:骁龙750G
          • +
          • 运行内存:8GB
          • +
          • 机身存储:256GB
          • +
          • 存储卡:支持MicroSD(TF)
          • +
          • 摄像头数量:后置四摄
          • +
          • 后摄主摄像素:1亿像素
          • +
          • 前摄主摄像素:1600万像素
          • +
          • 主屏幕尺寸(英寸):6.67英寸
          • +
          • 分辨率:全高清FHD+
          • +
          • 屏幕比例:19.6~20:9
          • +
          • 屏幕前摄组合:盲孔屏
          • +
          • 充电器:其他
          • +
          • 热点:人脸识别,快速充电,NFC,5G
          • +
          • 特殊功能:超大字体,超大音量,语音命令
          • +
          • 屏占比:≥92%
          • +
          • 操作系统:Android(安卓)
          • +
          • 游戏性能:发烧级
          • +
          • 充电功率:30-39W
          • +
          +

          + 更多参数>> +

          +
          + +
          +
          +
          +
          +
          + +
          +
          + +
          +
          +
          +
          商品介绍加载中...
          +
          + +
          +
          +
          +
            +
            +
            +
            +
            +
            +
            +
            +
            +
            +

            主体

            +
            +
            +
            入网型号
            +
            + +
            +
            +
            +

            工业代号或者入网型号

            +
            +
            +
            +
            以官网信息为准
            +
            +
            +
            品牌
            小米(MI)
            +
            +
            +
            产品名称
            Redmi Note9pro
            +
            +
            +
            上市年份
            2020年
            +
            +
            +
            首销日期
            以官网信息为准
            +
            +
            +
            上市月份
            11月
            +
            +
            +
            +
            +

            基本信息

            +
            +
            +
            机身长度(mm)
            165.38
            +
            +
            +
            机身重量(g)
            215
            +
            +
            +
            机身材质工艺
            以官网信息为准
            +
            +
            +
            机身宽度(mm)
            76.8
            +
            +
            +
            机身材质分类
            玻璃后盖
            +
            +
            +
            机身厚度(mm)
            9.0
            +
            +
            +
            运营商标志或内容
            +
            + +
            +
            +
            +

            定制机往往会有运营商的元素在手机的某些位置,该属性会介绍这些元素出现的位置。

            +
            +
            +
            +
            +
            +
            +
            输入方式
            触控
            +
            +
            +
            +
            +

            主芯片

            +
            +
            +
            CPU核数
            八核
            +
            +
            +
            CPU品牌
            高通(Qualcomm)
            +
            +
            +
            +
            +

            存储

            +
            +
            +
            最大存储扩展容量
            512GB
            +
            +
            +
            +
            +

            屏幕

            +
            +
            +
            屏幕材质类型
            LTPS LCD
            +
            +
            +
            屏幕色彩
            1670万色
            +
            +
            +
            屏幕刷新率
            120Hz
            +
            +
            +
            触摸屏实现方式
            ON-CELL
            +
            +
            +
            主屏幕尺寸(英寸)
            6.67英寸
            +
            +
            +
            触摸屏类型
            电容屏
            +
            +
            +
            +
            +

            后置摄像头

            +
            +
            +
            后摄主摄光圈
            f/1.75
            +
            +
            +
            闪光灯
            LED灯
            +
            +
            +
            后摄主摄光学防抖
            不支持光学防抖
            +
            +
            +
            后摄3摄像头的功能
            微距
            +
            +
            +
            +
            +

            前置摄像头

            +
            +
            +
            前摄主摄光圈
            其他
            +
            +
            +
            闪光灯
            其他
            +
            +
            +
            +
            +

            电池信息

            +
            +
            +
            电池是否可拆卸
            +
            + +
            +
            +
            +

            不可拆卸电池手机更加节省内部空间,密封性更好,请勿在没有专业人士的帮助下自行拆卸。

            +
            +
            +
            +
            电池不可拆卸
            +
            +
            +
            充电器
            其他
            +
            +
            +
            无线充电
            +
            + +
            +
            +
            +

            无线充电只是个功能,请注意支持无线充电的产品其包装是否带有无线充电的配件,如没有需要自行单配哦。

            +
            +
            +
            +
            不支持无线充电
            +
            +
            +
            +
            +

            网络支持

            +
            +
            +
            最大支持SIM卡数量
            2个
            +
            +
            +
            副卡网络频率
            以官网信息为准
            +
            +
            +
            网络频率(2G/3G)
            以官网信息为准
            +
            +
            +
            5G网络
            移动5G;联通5G;电信5G
            +
            +
            +
            4G网络
            +
            + +
            +
            +
            +

            单卡手机或者主卡的4G网络在这里填写,副卡的网络在副sim卡4G网络中填写。

            +
            +
            +
            +
            4G TD-LTE(移动);4G FDD-LTE(联通、电信)
            +
            +
            +
            双卡机类型
            双卡双待单通
            +
            +
            +
            3G/2G网络
            3G WCDMA(联通);3G CDMA2000(电信);2G GSM(移动/联通);2G CDMA(电信)
            +
            +
            +
            SIM卡类型
            +
            + +
            +
            +
            +

            sim卡的规格,大卡、小卡或者nano卡。如果副卡有不同可在下方副卡规格中填写或显示

            +
            +
            +
            +
            Nano SIM
            +
            +
            +
            +
            +

            数据接口

            +
            +
            +
            数据传输接口
            WIFI;蓝牙;红外
            +
            +
            +
            耳机接口类型
            3.5mm
            +
            +
            +
            充电接口类型
            Type-C
            +
            +
            +
            NFC/NFC模式
            支持(点对点模式);支持(读卡器模式);支持(卡模式)
            +
            +
            +
            +
            +

            手机特性

            +
            +
            +
            三防标准
            生活防水
            +
            +
            +
            +
            +

            娱乐功能

            +
            +
            +
            听筒扬声器
            听筒可作为扬声器使用立体声
            +
            +
            +
            mic数量
            2个
            +
            +
            +
            喇叭数量
            2个
            +
            +
            +
            +
            +

            辅助功能

            +
            +
            +
            常用功能
            便签;计算器;录音;超大字体;超大音量;语音识别
            +
            +
            +
            +
            +
            +

            包装清单

            +

            手机主机/电源适配器/USB Type-C数据线/手机保护壳/贴膜(已贴在屏幕上)/插针/说明书(内含三包凭证)

            +
            +
            +
            + +
            +
            + +
            +
            + +
            +
            + +
            +
            +
            +
            + +
            +
            +

            售后保障

            +
            +
            + +
            +
            +
            +
            +

            商品评价

            +
            +
            +
            +
            +
            + +
            +
            +
            推荐排序
            +
            +
            推荐排序
            +
              +
            • 推荐排序
            • +
            • 时间排序
            • +
            +
            +
            +
            +
            +
            +
            全部评论
            +
            正在加载中,请稍候...
            +
            正在加载中,请稍候...
            +
            正在加载中,请稍候...
            +
            正在加载中,请稍候...
            +
            +
            +
            +
            +
            +
            +

            商品问答

            +
            +
            +
            + 心中疑惑就问问买过此商品的同学吧~我要提问 +
            +
            +
            +
            +
            +
            + +
            +
            +
            +

            购买咨询

            +
            + +
            +
            +
            +
            +
            +
            +
            +
            +
            +
            +
            +
              +
            • 全部
            • +
            • 商品咨询
            • +
            • 库存配送
            • +
            • 支付
            • +
            • 发票保修
            • +
            • +
            +
            +
            + +
            +
            +
            +
            +
            + +
            +
            +
            +
            + + + + + + + +
            + + + + + + +
            + + + + diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/search_jd.html" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/search_jd.html" new file mode 100644 index 00000000..012f1af8 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/search_jd.html" @@ -0,0 +1,5284 @@ + + + + + + + + + + + + + + + + + + + + +手机 - 商品搜索 - 京东 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            +
            + + + +
            +
            +
            +
            +
            + +
            +
            +
              +
              + + +
              +
              +
              +
              + + + 我的购物车 +
              +
              +
              +
              + +
              +
              +
              +
              + +
              + + +
              + + +
              +
              +
              +
              + +
              + > +
              + "手机" +
              +
              +
              +
              + +
              + +
              + +
              +
              +
              品牌:
              +
              +
                +
              • 所有品牌
              • +
              • A
              • +
              • B
              • +
              • C
              • +
              • D
              • +
              • E
              • +
              • F
              • +
              • G
              • +
              • H
              • +
              • I
              • +
              • J
              • +
              • K
              • +
              • L
              • +
              • M
              • +
              • N
              • +
              • O
              • +
              • P
              • +
              • R
              • +
              • S
              • +
              • T
              • +
              • U
              • +
              • V
              • +
              • X
              • +
              • Y
              • +
              • Z
              • +
              +
              +
              + +
              +
              已选条件:
                +
                + 确定 + 取消 +
                +
                +
                + 更多 + 多选 +
                +
                +
                +
                +
                +
                分类:
                +
                +
                + +
                +
                + 确定 + 取消 +
                +
                +
                + 更多 + +
                +
                +
                + +
                +
                +
                CPU型号:
                +
                +
                + +
                +
                + 确定 + 取消 +
                +
                +
                + 更多 + 多选 +
                +
                +
                +
                +
                +
                运行内存:
                +
                +
                + +
                +
                + 确定 + 取消 +
                +
                +
                + 更多 + 多选 +
                +
                +
                +
                +
                +
                高级选项:
                + +
                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                +
                +
                +
                +
                +
                + +
                +
                + +
                + + + + + +
                +
                +
                +
                + - +
                +
                +
                + + 清空 + 确定 +
                +
                +
                + + 1/99 + + < + > +
                +
                5900+件商品
                + +
                +
                +
                +
                配送至
                +
                +
                +
                北京
                + +
                +
                +
                +
                +
                +
                +
                + + +
                +
                + + +
                + + + +
                +
                正在加载中,请稍后~~
                +
                +
                +
                +
                +
                +
                + +

                商品精选

                +
                +
                  +
                +
                +
                +

                精品推荐

                + +
                +
                + +
                + + +
                +
                +
                +
                +
                + +
                商品精选
                +
                +
                +
                +
                + +
                +
                +
                +
                + +
                +
                +
                  +
                1. + 品类齐全,轻松购物 +
                2. +
                3. + 多仓直发,极速配送 +
                4. +
                5. + 正品行货,精致服务 +
                6. +
                7. + 天天低价,畅选无忧 +
                8. +
                +
                +
                +
                +
                +
                +
                购物指南
                +
                + 购物流程 +
                +
                + 会员介绍 +
                +
                + 生活旅行/团购 +
                +
                + 常见问题 +
                +
                + 大家电 +
                +
                + 联系客服 +
                +
                +
                +
                配送方式
                +
                + 上门自提 +
                +
                + 211限时达 +
                +
                + 配送服务查询 +
                +
                + 配送费收取标准 +
                +
                + 海外配送 +
                +
                +
                +
                支付方式
                +
                + 货到付款 +
                +
                + 在线支付 +
                +
                + 分期付款 +
                +
                + 公司转账 +
                +
                +
                +
                售后服务
                +
                + 售后政策 +
                +
                + 价格保护 +
                +
                + 退款说明 +
                +
                + 返修/退换货 +
                +
                + 取消订单 +
                +
                +
                +
                特色服务
                +
                + 夺宝岛 +
                +
                + DIY装机 +
                +
                + 延保服务 +
                +
                + 京东E卡 +
                +
                + 京东通信 +
                +
                + 京鱼座智能 +
                +
                + +
                +
                +
                +
                + + +
                + + + + + diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..69f0d52c --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\344\275\234\344\270\232.py" @@ -0,0 +1,45 @@ +# -*- coding: UTF-8 -*- +""" +@File :第九周-作业.py +@Author :Super +@Date :2021/2/24 +@Desc : +""" +import requests +import json + +headers = { + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36' +} + + +def search_jd(keyword): + url = f'https://search.jd.com/Search?keyword={keyword}&enc=utf-8' + response = requests.get(url, headers=headers) + with open('search_jd.html', 'wb') as f: + f.write(response.content) + + +def detail_jd(): + url = 'https://item.jd.com/100016799388.html' + response = requests.get(url, headers=headers) + with open('detail_jd.html', 'wb') as f: + f.write(response.content) + + +test_dict = { + "a": 1, + "b": ["1", 2, None], + "c": {"d": 1} +} +# json格式数据其实是个字符串 +# 将python字典转变为json数据格式 +json_data = json.dumps(test_dict) +print(type(json_data), json_data) + +# 将json数据格式转变为字典 +print(json.loads(json_data)) + +if __name__ == '__main__': + search_jd('手机') + detail_jd() -- Gitee From 9154d239bab46d6e92d7d7d979c54084d112e65f Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Sun, 28 Feb 2021 18:43:20 +0800 Subject: [PATCH 26/27] =?UTF-8?q?=E7=AC=AC=E4=B9=9D=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E8=8A=82=E5=92=8C=E7=AC=AC=E4=B8=89=E8=8A=82=20?= =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../week9/jd_crawler/main.py" | 72 + .../week9/jd_crawler/parsers/detail.py" | 7 + .../week9/jd_crawler/parsers/search.py" | 38 + .../week9/jd_crawler/settings.py" | 19 + .../week9/jd_crawler/test/search_jd.html" | 5284 +++++++++++++++++ ...4\350\212\202-\344\275\234\344\270\232.py" | 16 + 6 files changed, 5436 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/main.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/detail.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/search.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/settings.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/test/search_jd.html" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/main.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/main.py" new file mode 100644 index 00000000..4945eecf --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/main.py" @@ -0,0 +1,72 @@ +# -*- coding: UTF-8 -*- +""" +@File :main.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" +import threading +import multiprocessing +import pymysql +import requests + +from parsers.search import parse_jd_item +from settings import MYSQL_CONF, HEADERS + + +def save(item_array): + """ + 持久化保存抓取结果 + :param item_array: + :return: + """ + cursor = mysql_con.cursor() + SQL = """INSERT INTO jd_search(sku_id, img, price, title, shop, icons) + VALUES (%s, %s, %s, %s, %s, %s)""" + cursor.executemany(SQL, item_array) + mysql_con.commit() + cursor.close() + + +def downloader(task): + """ + 请求目标网址的组件 + :param task: + :return: + """ + url = "https://search.jd.com/Search" + params = { + "keyword": task + } + res = requests.get(url, params=params, headers=HEADERS) + return res + + +def main(task_array, mysql_con): + """ + 爬虫任务的调度 + :param task_array: + :return: + """ + # for task in task_array: + result = downloader(task_array) + item_array = parse_jd_item(result.text) + print(item_array) + save(item_array) + + +if __name__ == '__main__': + mysql_con = pymysql.connect(**MYSQL_CONF) + task_array = ["鼠标","键盘","显卡", "耳机"] + pro_list = [] + for item in task_array: + p = multiprocessing.Process(target=main, args=(item, )) + pro_list.append(p) + p.start() + for i in pro_list: + i.join() + + print("Process end.") + # main(task_array) + # t1 = threading.Thread(target=main, args=(task_array, )) # 多线程版本 + # t1.start() \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/detail.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/detail.py" new file mode 100644 index 00000000..24f172fb --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/detail.py" @@ -0,0 +1,7 @@ +# -*- coding: UTF-8 -*- +""" +@File :detail.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/search.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/search.py" new file mode 100644 index 00000000..9ad46f85 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/parsers/search.py" @@ -0,0 +1,38 @@ +# -*- coding: UTF-8 -*- +""" +@File :search.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" +import json + +from bs4 import BeautifulSoup + +def parse_jd_item(html): + result = [] + soup = BeautifulSoup(html, "lxml") + item_array = soup.select("ul[class='gl-warp clearfix'] li[class='gl-item']") + for item in item_array: + sku_id = item.attrs['data-sku'] + img = item.select("img[data-img='1']") + price = item.select("div[class='p-price']") + title = item.select("div[class='p-name p-name-type-2']") + shop = item.select("div[class='p-shop']") + icons = item.select("div[class='p-icons']") + + img = img[0].attrs['data-lazy-img'] if img else "" + price = price[0].strong.i.text if price else "" + title = title[0].text.strip() if title else "" + shop = shop[0].span.a.attrs['title'] if shop[0].text.strip() else "" + icons = json.dumps([tag_ele.text for tag_ele in icons[0].select('i')]) if icons else '[]' + + result.append((sku_id, img, price, title, shop, icons)) + return result + + +if __name__ == '__main__': + with open("../test/search_jd.html", "r", encoding="utf-8") as f: + html = f.read() + result = parse_jd_item(html) + print(result) \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/settings.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/settings.py" new file mode 100644 index 00000000..f70a3bf3 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/settings.py" @@ -0,0 +1,19 @@ +# -*- coding: UTF-8 -*- +""" +@File :settings.py +@Author :Super +@Date :2021/2/28 +@Desc :当前爬虫项目基础配置文件,目的统一化配置,避免重复修改 +""" + +HEADERS = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36", + "upgrade-insecure-requests": "1" +} + +MYSQL_CONF = { + "host": "127.0.0.1", + "user": "root", + "password": "123456", + "db": "world" +} \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/test/search_jd.html" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/test/search_jd.html" new file mode 100644 index 00000000..012f1af8 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/jd_crawler/test/search_jd.html" @@ -0,0 +1,5284 @@ + + + + + + + + + + + + + + + + + + + + +手机 - 商品搜索 - 京东 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                +
                + + + +
                +
                +
                +
                +
                + +
                +
                +
                  +
                  + + +
                  +
                  +
                  +
                  + + + 我的购物车 +
                  +
                  +
                  +
                  + +
                  +
                  +
                  +
                  + +
                  + + +
                  + + +
                  +
                  +
                  +
                  + +
                  + > +
                  + "手机" +
                  +
                  +
                  +
                  + +
                  + +
                  + +
                  +
                  +
                  品牌:
                  +
                  +
                    +
                  • 所有品牌
                  • +
                  • A
                  • +
                  • B
                  • +
                  • C
                  • +
                  • D
                  • +
                  • E
                  • +
                  • F
                  • +
                  • G
                  • +
                  • H
                  • +
                  • I
                  • +
                  • J
                  • +
                  • K
                  • +
                  • L
                  • +
                  • M
                  • +
                  • N
                  • +
                  • O
                  • +
                  • P
                  • +
                  • R
                  • +
                  • S
                  • +
                  • T
                  • +
                  • U
                  • +
                  • V
                  • +
                  • X
                  • +
                  • Y
                  • +
                  • Z
                  • +
                  +
                  +
                  + +
                  +
                  已选条件:
                    +
                    + 确定 + 取消 +
                    +
                    +
                    + 更多 + 多选 +
                    +
                    +
                    +
                    +
                    +
                    分类:
                    +
                    +
                    + +
                    +
                    + 确定 + 取消 +
                    +
                    +
                    + 更多 + +
                    +
                    +
                    + +
                    +
                    +
                    CPU型号:
                    +
                    +
                    + +
                    +
                    + 确定 + 取消 +
                    +
                    +
                    + 更多 + 多选 +
                    +
                    +
                    +
                    +
                    +
                    运行内存:
                    +
                    +
                    + +
                    +
                    + 确定 + 取消 +
                    +
                    +
                    + 更多 + 多选 +
                    +
                    +
                    +
                    +
                    +
                    高级选项:
                    + +
                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                    +
                    +
                    +
                    +
                    +
                    + +
                    +
                    + +
                    + + + + + +
                    +
                    +
                    +
                    + - +
                    +
                    +
                    + + 清空 + 确定 +
                    +
                    +
                    + + 1/99 + + < + > +
                    +
                    5900+件商品
                    + +
                    +
                    +
                    +
                    配送至
                    +
                    +
                    +
                    北京
                    + +
                    +
                    +
                    +
                    +
                    +
                    +
                    + + +
                    +
                    + + +
                    + + + +
                    +
                    正在加载中,请稍后~~
                    +
                    +
                    +
                    +
                    +
                    +
                    + +

                    商品精选

                    +
                    +
                      +
                    +
                    +
                    +

                    精品推荐

                    + +
                    +
                    + +
                    + + +
                    +
                    +
                    +
                    +
                    + +
                    商品精选
                    +
                    +
                    +
                    +
                    + +
                    +
                    +
                    +
                    + +
                    +
                    +
                      +
                    1. + 品类齐全,轻松购物 +
                    2. +
                    3. + 多仓直发,极速配送 +
                    4. +
                    5. + 正品行货,精致服务 +
                    6. +
                    7. + 天天低价,畅选无忧 +
                    8. +
                    +
                    +
                    +
                    +
                    +
                    +
                    购物指南
                    +
                    + 购物流程 +
                    +
                    + 会员介绍 +
                    +
                    + 生活旅行/团购 +
                    +
                    + 常见问题 +
                    +
                    + 大家电 +
                    +
                    + 联系客服 +
                    +
                    +
                    +
                    配送方式
                    +
                    + 上门自提 +
                    +
                    + 211限时达 +
                    +
                    + 配送服务查询 +
                    +
                    + 配送费收取标准 +
                    +
                    + 海外配送 +
                    +
                    +
                    +
                    支付方式
                    +
                    + 货到付款 +
                    +
                    + 在线支付 +
                    +
                    + 分期付款 +
                    +
                    + 公司转账 +
                    +
                    +
                    +
                    售后服务
                    +
                    + 售后政策 +
                    +
                    + 价格保护 +
                    +
                    + 退款说明 +
                    +
                    + 返修/退换货 +
                    +
                    + 取消订单 +
                    +
                    +
                    +
                    特色服务
                    +
                    + 夺宝岛 +
                    +
                    + DIY装机 +
                    +
                    + 延保服务 +
                    +
                    + 京东E卡 +
                    +
                    + 京东通信 +
                    +
                    + 京鱼座智能 +
                    +
                    + +
                    +
                    +
                    +
                    + + +
                    + + + + + diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" new file mode 100644 index 00000000..0c47e656 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week9/\347\254\254\344\271\235\345\221\250-\347\254\254\344\272\214\350\212\202-\344\275\234\344\270\232.py" @@ -0,0 +1,16 @@ +# -*- coding: UTF-8 -*- +""" +@File :第九周-第二节-作业.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" +from bs4 import BeautifulSoup + +with open('search_jd.html', 'r', encoding='utf-8') as f: + html_str = f.read() + +soup = BeautifulSoup(html_str, 'lxml') +items = soup.select("ul[class='J_valueList v-fixed'] li a") +for item in items: + print(item.text.strip()) \ No newline at end of file -- Gitee From 7fa075d210cfc58c64cf05702103f9960301ac8e Mon Sep 17 00:00:00 2001 From: Super-Coding <1125699801@qq.com> Date: Thu, 4 Mar 2021 22:47:15 +0800 Subject: [PATCH 27/27] =?UTF-8?q?=E7=AC=AC=E5=8D=81=E5=91=A8-=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E8=8A=82=E5=92=8C=E7=AC=AC=E4=BA=8C=E8=8A=82=20?= =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../week10/jd_crawler/main.py" | 63 + .../week10/jd_crawler/parsers/detail.py" | 7 + .../week10/jd_crawler/parsers/search.py" | 38 + .../week10/jd_crawler/settings.py" | 19 + .../week10/jd_crawler/test/parser_test.py" | 17 + .../week10/jd_crawler/test/search_jd.html" | 5284 +++++++++++++++++ .../jd_crawlers/jd_crawlers/__init__.py" | 0 .../week10/jd_crawlers/jd_crawlers/items.py" | 12 + .../jd_crawlers/jd_crawlers/middlewares.py" | 103 + .../jd_crawlers/jd_crawlers/pipelines.py" | 13 + .../jd_crawlers/jd_crawlers/settings.py" | 88 + .../jd_crawlers/spiders/__init__.py" | 4 + .../jd_crawlers/spiders/jd_spider.py" | 25 + .../week10/jd_crawlers/scrapy.cfg" | 11 + 14 files changed, 5684 insertions(+) create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/main.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/detail.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/search.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/settings.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/parser_test.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/search_jd.html" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/__init__.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/items.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/middlewares.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/pipelines.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/settings.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/__init__.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/jd_spider.py" create mode 100644 "\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/scrapy.cfg" diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/main.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/main.py" new file mode 100644 index 00000000..966726de --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/main.py" @@ -0,0 +1,63 @@ +# -*- coding: UTF-8 -*- +""" +@File :main.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" +import threading +import multiprocessing +import pymysql +import requests + +from parsers.search import parse_jd_item +from settings import MYSQL_CONF, HEADERS + + +def save(item_array): + """ + 持久化保存抓取结果 + :param item_array: + :return: + """ + cursor = mysql_con.cursor() + SQL = """INSERT INTO jd_search(sku_id, img, price, title, shop, icons) + VALUES (%s, %s, %s, %s, %s, %s)""" + cursor.executemany(SQL, item_array) + mysql_con.commit() + cursor.close() + + +def downloader(task): + """ + 请求目标网址的组件 + :param task: + :return: + """ + url = "https://search.jd.com/Search" + params = { + "keyword": task + } + res = requests.get(url, params=params, headers=HEADERS) + return res + + +def main(task_array): + """ + 爬虫任务的调度 + :param task_array: + :return: + """ + for task in task_array: + result = downloader(task) + item_array = parse_jd_item(result.text) + print(item_array) + save(item_array) + + +if __name__ == '__main__': + mysql_con = pymysql.connect(**MYSQL_CONF) + task_array = ["鼠标","键盘","显卡", "耳机"] + main(task_array) + # t1 = threading.Thread(target=main, args=(task_array, )) # 多线程版本 + # t1.start() \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/detail.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/detail.py" new file mode 100644 index 00000000..24f172fb --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/detail.py" @@ -0,0 +1,7 @@ +# -*- coding: UTF-8 -*- +""" +@File :detail.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/search.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/search.py" new file mode 100644 index 00000000..9ad46f85 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/parsers/search.py" @@ -0,0 +1,38 @@ +# -*- coding: UTF-8 -*- +""" +@File :search.py +@Author :Super +@Date :2021/2/28 +@Desc : +""" +import json + +from bs4 import BeautifulSoup + +def parse_jd_item(html): + result = [] + soup = BeautifulSoup(html, "lxml") + item_array = soup.select("ul[class='gl-warp clearfix'] li[class='gl-item']") + for item in item_array: + sku_id = item.attrs['data-sku'] + img = item.select("img[data-img='1']") + price = item.select("div[class='p-price']") + title = item.select("div[class='p-name p-name-type-2']") + shop = item.select("div[class='p-shop']") + icons = item.select("div[class='p-icons']") + + img = img[0].attrs['data-lazy-img'] if img else "" + price = price[0].strong.i.text if price else "" + title = title[0].text.strip() if title else "" + shop = shop[0].span.a.attrs['title'] if shop[0].text.strip() else "" + icons = json.dumps([tag_ele.text for tag_ele in icons[0].select('i')]) if icons else '[]' + + result.append((sku_id, img, price, title, shop, icons)) + return result + + +if __name__ == '__main__': + with open("../test/search_jd.html", "r", encoding="utf-8") as f: + html = f.read() + result = parse_jd_item(html) + print(result) \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/settings.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/settings.py" new file mode 100644 index 00000000..f70a3bf3 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/settings.py" @@ -0,0 +1,19 @@ +# -*- coding: UTF-8 -*- +""" +@File :settings.py +@Author :Super +@Date :2021/2/28 +@Desc :当前爬虫项目基础配置文件,目的统一化配置,避免重复修改 +""" + +HEADERS = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36", + "upgrade-insecure-requests": "1" +} + +MYSQL_CONF = { + "host": "127.0.0.1", + "user": "root", + "password": "123456", + "db": "world" +} \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/parser_test.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/parser_test.py" new file mode 100644 index 00000000..c87f6ef9 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/parser_test.py" @@ -0,0 +1,17 @@ +# -*- coding: UTF-8 -*- +""" +@File :parser_test.py +@Author :Super +@Date :2021/3/4 +@Desc : +""" +import sys +import os + +sys.path.append(os.getcwd()) +from parsers.search import parse_jd_item + +with open("test/search_jd.html", "r", encoding="utf-8") as f: + html = f.read() +result = parse_jd_item(html) +print(result) \ No newline at end of file diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/search_jd.html" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/search_jd.html" new file mode 100644 index 00000000..012f1af8 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawler/test/search_jd.html" @@ -0,0 +1,5284 @@ + + + + + + + + + + + + + + + + + + + + +手机 - 商品搜索 - 京东 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                    +
                    + + + +
                    +
                    +
                    +
                    +
                    + +
                    +
                    +
                      +
                      + + +
                      +
                      +
                      +
                      + + + 我的购物车 +
                      +
                      +
                      +
                      + +
                      +
                      +
                      +
                      + +
                      + + +
                      + + +
                      +
                      +
                      +
                      + +
                      + > +
                      + "手机" +
                      +
                      +
                      +
                      + +
                      + +
                      + +
                      +
                      +
                      品牌:
                      +
                      +
                        +
                      • 所有品牌
                      • +
                      • A
                      • +
                      • B
                      • +
                      • C
                      • +
                      • D
                      • +
                      • E
                      • +
                      • F
                      • +
                      • G
                      • +
                      • H
                      • +
                      • I
                      • +
                      • J
                      • +
                      • K
                      • +
                      • L
                      • +
                      • M
                      • +
                      • N
                      • +
                      • O
                      • +
                      • P
                      • +
                      • R
                      • +
                      • S
                      • +
                      • T
                      • +
                      • U
                      • +
                      • V
                      • +
                      • X
                      • +
                      • Y
                      • +
                      • Z
                      • +
                      +
                      +
                      + +
                      +
                      已选条件:
                        +
                        + 确定 + 取消 +
                        +
                        +
                        + 更多 + 多选 +
                        +
                        +
                        +
                        +
                        +
                        分类:
                        +
                        +
                        + +
                        +
                        + 确定 + 取消 +
                        +
                        +
                        + 更多 + +
                        +
                        +
                        + +
                        +
                        +
                        CPU型号:
                        +
                        +
                        + +
                        +
                        + 确定 + 取消 +
                        +
                        +
                        + 更多 + 多选 +
                        +
                        +
                        +
                        +
                        +
                        运行内存:
                        +
                        +
                        + +
                        +
                        + 确定 + 取消 +
                        +
                        +
                        + 更多 + 多选 +
                        +
                        +
                        +
                        +
                        +
                        高级选项:
                        + +
                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                        +
                        +
                        +
                        +
                        +
                        + +
                        +
                        + +
                        + + + + + +
                        +
                        +
                        +
                        + - +
                        +
                        +
                        + + 清空 + 确定 +
                        +
                        +
                        + + 1/99 + + < + > +
                        +
                        5900+件商品
                        + +
                        +
                        +
                        +
                        配送至
                        +
                        +
                        +
                        北京
                        + +
                        +
                        +
                        +
                        +
                        +
                        +
                        + + +
                        +
                        + + +
                        + + + +
                        +
                        正在加载中,请稍后~~
                        +
                        +
                        +
                        +
                        +
                        +
                        + +

                        商品精选

                        +
                        +
                          +
                        +
                        +
                        +

                        精品推荐

                        + +
                        +
                        + +
                        + + +
                        +
                        +
                        +
                        +
                        + +
                        商品精选
                        +
                        +
                        +
                        +
                        + +
                        +
                        +
                        +
                        + +
                        +
                        +
                          +
                        1. + 品类齐全,轻松购物 +
                        2. +
                        3. + 多仓直发,极速配送 +
                        4. +
                        5. + 正品行货,精致服务 +
                        6. +
                        7. + 天天低价,畅选无忧 +
                        8. +
                        +
                        +
                        +
                        +
                        +
                        +
                        购物指南
                        +
                        + 购物流程 +
                        +
                        + 会员介绍 +
                        +
                        + 生活旅行/团购 +
                        +
                        + 常见问题 +
                        +
                        + 大家电 +
                        +
                        + 联系客服 +
                        +
                        +
                        +
                        配送方式
                        +
                        + 上门自提 +
                        +
                        + 211限时达 +
                        +
                        + 配送服务查询 +
                        +
                        + 配送费收取标准 +
                        +
                        + 海外配送 +
                        +
                        +
                        +
                        支付方式
                        +
                        + 货到付款 +
                        +
                        + 在线支付 +
                        +
                        + 分期付款 +
                        +
                        + 公司转账 +
                        +
                        +
                        +
                        售后服务
                        +
                        + 售后政策 +
                        +
                        + 价格保护 +
                        +
                        + 退款说明 +
                        +
                        + 返修/退换货 +
                        +
                        + 取消订单 +
                        +
                        +
                        +
                        特色服务
                        +
                        + 夺宝岛 +
                        +
                        + DIY装机 +
                        +
                        + 延保服务 +
                        +
                        + 京东E卡 +
                        +
                        + 京东通信 +
                        +
                        + 京鱼座智能 +
                        +
                        + +
                        +
                        +
                        +
                        + + +
                        + + + + + diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/__init__.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/__init__.py" new file mode 100644 index 00000000..e69de29b diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/items.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/items.py" new file mode 100644 index 00000000..67c1e691 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/items.py" @@ -0,0 +1,12 @@ +# Define here the models for your scraped items +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class JdCrawlersItem(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/middlewares.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/middlewares.py" new file mode 100644 index 00000000..e8457d0c --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/middlewares.py" @@ -0,0 +1,103 @@ +# Define here the models for your spider middleware +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + +# useful for handling different item types with a single interface +from itemadapter import is_item, ItemAdapter + + +class JdCrawlersSpiderMiddleware: + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the spider middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_spider_input(self, response, spider): + # Called for each response that goes through the spider + # middleware and into the spider. + + # Should return None or raise an exception. + return None + + def process_spider_output(self, response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, or item objects. + for i in result: + yield i + + def process_spider_exception(self, response, exception, spider): + # Called when a spider or process_spider_input() method + # (from other spider middleware) raises an exception. + + # Should return either None or an iterable of Request or item objects. + pass + + def process_start_requests(self, start_requests, spider): + # Called with the start requests of the spider, and works + # similarly to the process_spider_output() method, except + # that it doesn’t have a response associated. + + # Must return only requests (not items). + for r in start_requests: + yield r + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) + + +class JdCrawlersDownloaderMiddleware: + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the downloader middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_request(self, request, spider): + # Called for each request that goes through the downloader + # middleware. + + # Must either: + # - return None: continue processing this request + # - or return a Response object + # - or return a Request object + # - or raise IgnoreRequest: process_exception() methods of + # installed downloader middleware will be called + return None + + def process_response(self, request, response, spider): + # Called with the response returned from the downloader. + + # Must either; + # - return a Response object + # - return a Request object + # - or raise IgnoreRequest + return response + + def process_exception(self, request, exception, spider): + # Called when a download handler or a process_request() + # (from other downloader middleware) raises an exception. + + # Must either: + # - return None: continue processing this exception + # - return a Response object: stops process_exception() chain + # - return a Request object: stops process_exception() chain + pass + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/pipelines.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/pipelines.py" new file mode 100644 index 00000000..ccc9b0a4 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/pipelines.py" @@ -0,0 +1,13 @@ +# Define your item pipelines here +# +# Don't forget to add your pipeline to the ITEM_PIPELINES setting +# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html + + +# useful for handling different item types with a single interface +from itemadapter import ItemAdapter + + +class JdCrawlersPipeline: + def process_item(self, item, spider): + return item diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/settings.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/settings.py" new file mode 100644 index 00000000..846c0a1d --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/settings.py" @@ -0,0 +1,88 @@ +# Scrapy settings for jd_crawlers project +# +# For simplicity, this file contains only settings considered important or +# commonly used. You can find more settings consulting the documentation: +# +# https://docs.scrapy.org/en/latest/topics/settings.html +# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +BOT_NAME = 'jd_crawlers' + +SPIDER_MODULES = ['jd_crawlers.spiders'] +NEWSPIDER_MODULE = 'jd_crawlers.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'jd_crawlers (+http://www.yourdomain.com)' + +# Obey robots.txt rules +ROBOTSTXT_OBEY = True + +# Configure maximum concurrent requests performed by Scrapy (default: 16) +#CONCURRENT_REQUESTS = 32 + +# Configure a delay for requests for the same website (default: 0) +# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay +# See also autothrottle settings and docs +#DOWNLOAD_DELAY = 3 +# The download delay setting will honor only one of: +#CONCURRENT_REQUESTS_PER_DOMAIN = 16 +#CONCURRENT_REQUESTS_PER_IP = 16 + +# Disable cookies (enabled by default) +#COOKIES_ENABLED = False + +# Disable Telnet Console (enabled by default) +#TELNETCONSOLE_ENABLED = False + +# Override the default request headers: +#DEFAULT_REQUEST_HEADERS = { +# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', +# 'Accept-Language': 'en', +#} + +# Enable or disable spider middlewares +# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html +#SPIDER_MIDDLEWARES = { +# 'jd_crawlers.middlewares.JdCrawlersSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'jd_crawlers.middlewares.JdCrawlersDownloaderMiddleware': 543, +#} + +# Enable or disable extensions +# See https://docs.scrapy.org/en/latest/topics/extensions.html +#EXTENSIONS = { +# 'scrapy.extensions.telnet.TelnetConsole': None, +#} + +# Configure item pipelines +# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html +#ITEM_PIPELINES = { +# 'jd_crawlers.pipelines.JdCrawlersPipeline': 300, +#} + +# Enable and configure the AutoThrottle extension (disabled by default) +# See https://docs.scrapy.org/en/latest/topics/autothrottle.html +#AUTOTHROTTLE_ENABLED = True +# The initial download delay +#AUTOTHROTTLE_START_DELAY = 5 +# The maximum download delay to be set in case of high latencies +#AUTOTHROTTLE_MAX_DELAY = 60 +# The average number of requests Scrapy should be sending in parallel to +# each remote server +#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 +# Enable showing throttling stats for every response received: +#AUTOTHROTTLE_DEBUG = False + +# Enable and configure HTTP caching (disabled by default) +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings +#HTTPCACHE_ENABLED = True +#HTTPCACHE_EXPIRATION_SECS = 0 +#HTTPCACHE_DIR = 'httpcache' +#HTTPCACHE_IGNORE_HTTP_CODES = [] +#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/__init__.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/__init__.py" new file mode 100644 index 00000000..ebd689ac --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/__init__.py" @@ -0,0 +1,4 @@ +# This package will contain the spiders of your Scrapy project +# +# Please refer to the documentation for information on how to create and manage +# your spiders. diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/jd_spider.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/jd_spider.py" new file mode 100644 index 00000000..5b716544 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/jd_crawlers/spiders/jd_spider.py" @@ -0,0 +1,25 @@ +# -*- coding: UTF-8 -*- +""" +@File :jd_spider.py +@Author :Super +@Date :2021/3/4 +@Desc : +""" +import scrapy + + +class JdSpider(scrapy.Spider): + name = 'jd_spider' + + def start_requests(self): + for item in ["鼠标", "键盘", "显卡", "耳机"]: + for page in range(1, 10): + url = f'https://search.jd.com/Search?keyword={item}&wq={item}&page={page}' + yield scrapy.FormRequest( + url=url, + method='GET', + callback=self.parse_jd, # 指定回调函数处理response对象 + ) + + def parse_jd(self, response): + print(response) diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/scrapy.cfg" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/scrapy.cfg" new file mode 100644 index 00000000..0efdfa54 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Super_Coding/week10/jd_crawlers/scrapy.cfg" @@ -0,0 +1,11 @@ +# Automatically created by: scrapy startproject +# +# For more information about the [deploy] section see: +# https://scrapyd.readthedocs.io/en/latest/deploy.html + +[settings] +default = jd_crawlers.settings + +[deploy] +#url = http://localhost:6800/ +project = jd_crawlers -- Gitee