1. 函数
(1). 基础
a. 定义
- 一段具有****特定功能的、可重复使用的语句组合,用函数名(小写)来表示并调用,使用
def
关键字标识
b. 分类
- 自定义函数
- 内置函数
(2). 调用步骤
调用处暂停执行 => 实参赋值给形参 => 执行函数体语句 => 给出返回值,继续执行调用前语句
(3). 常见内置函数
2. 类
(1). 定义
- 具有相同属性和方法对象的集合是类;类中的函数称为****方法;类中的变量称为属性;实例化后的类(大写)称为对象
(2). 使用
a. 内部调用
- self.<方法名>(参数列表)
class MyClass: def fuc1(self): print('a') self.common_func() #内部调用方法 def common_func(self): pass
b. 外部调用
- <实例名>.<方法名>(参数列表)
class Person: def say(self): print('hello') p = Person() p.say() #外部调用方法
3. 文件操作
(1). 操作步骤
- open()打开对象文件 => 操作对象文件 => close()关闭对象文件,释放资源
(2). 模式选择
(3). 具体操作
a. 打开/新建文件
- 实质为打开****python shell 与磁盘上文件之间的连接
①语法
fileobj = (filename,[,mode[,buffering]])
②实例
file = open('1.txt','w',encoding='utf-8')
print(file)
b. 读取文件
- 涉及3个函数
方法 | 描述 |
---|---|
read() | **读取指定字节为一个字符串,**默认为全部 |
readline() | 读取一行为一个字符串 |
readlines() | **读取多行,返回列表,**默认为全部 |
c. 写入文件
①方法
方法 | 描述 |
---|---|
write(str) | 写入****指定字符串,返回写入的字节数 |
writelines(sequence) | 写入****多行 |
②实例
-
write()
f1 = open('1.txt','w',100,encoding='utf-8') f1.write('写入:abc') f1.flush() #强制写入 f1.close()
-
writelines()
- 不限数据类型,只要元素的数据类型为字符串类型;字典只能写入key值
f1 = open('1.txt','w',100,encoding='utf-8') set1 = {'hello','world','!'} f1.writelines(set1) f1.flush() f1.close()
d. 关闭文件
- 使用****close()方法,如果使用with语句,则会自动关闭文件,包括产生异常时
4. 正则表达式
(1). 基础
a. 定义
- 通过某种****规则来匹配符合规则的序列
b. 用途
- 处理文本和数据
- 数据清洗:爬虫、数据挖掘、自然语言处理等
c. 使用流程
- 编写****Pattern实例
- 通过Pattern实例匹配出结果****March
- 使用March实例****获得信息
(2). 函数
a. match()
①定义
- 尝试从字符串的****起始位置匹配一个模式,起始位置匹配失败则返回None
②语法
re.match(pattern,string,flags=0)
方法 | 描述 |
---|---|
group(num=0) | 匹配整个表达式的字符串,可以依次输入多个组号,因此返回值是一个元组 |
groups() | 返回一个包含所有小组字符串的元组,从1到所含的小组号 |
⑥实例
import re
m = re.search(r'hello','hello world!')
print(m.group())
b. search()
①定义
- 扫描整个字符串,返回第一个匹配成功的值
②语法
re.search(pattern,[flages])
参数 | 描述 |
---|---|
pattern | 匹配的正则表达式 |
string | 要匹配的字符串 |
flags | 用于控制正则表达式的匹配方式:是否区分大小写,多行匹配等 |
c. compile()
①定义
- 用于编译正则表达式,即****生成pattern的内容
②语法
import re
pattern = re.compile('hello')
m = pattern.match('hello world')
print(m.group())
d. findall()
①定义
- 匹配所有符合正则表达式的部分,返回一个列表
②语法
re.findall(pattern,string)
③实例
import re
m = re.findall('hello','world hello hello 1234 helword hello')
print(m)
e. 区别
函数 | 特点 |
---|---|
match() | 从****开始进行匹配,开头失败则返回None |
search() | 单次匹配整个字符串 |
findall() | 返回匹配的****所有值,以列表形式 |
compile() | 生成正则表达式,供match()、search()、findall()等函数使用 |
5. 模块
(1). 定义
- 以
.py
结尾的Python文件都是一个模块
(2). 导入
a. 导入
from module import * #导入模块所有内容,不建议使用
from module import xxx #导入模块指定内容
from module import xxx as yyy #导入模块指定内容并取别名
import module #推荐使用
b. 注意
- 模块名不能与Python内置模块冲突
- 导入同名函数,采用就近原则进行覆盖
(3). 推荐写法
#导入模块
#定义全局变量
#定义类
#定义函数
#测试代码
if__name__ == "__main__":
main()
#测试函数
def main():
pass
(4). 常用内置模块
a. os
- 封装了与操作系统相关的函数
b. 时间模块
- 包含时间处理的函数
c. random
- 随机返回生成的一个实数
d. sys
- 提供系统相关的参数和函数
e. subprocess
①run()
import subprocess
subprocess.run('whoami')
②Popen()
import subprocess
subprocess.Popen(['whoami'],stdout=subporcess.PIPE,stderr=subprocess.PIPE,text=True)
stdout,stderr = p.communicate()
print('标准输入',stdout)
print('标准错误',stderr)
6. 爬虫
(1). 基础
a. 定义
- 是一种按照****一定的规则,自动抓取网络信息的程序或脚本
b. 使用思路
- 构造目标网址
- 发起请求(request)
- 获取网页内容(request)
- 定制筛选器
- 保存爬取结果
(2). Requests模块
- **支持HTTP连接保持和连接池、**cookie保持会话、文件上传、自动响应内容的编码
requests.request(method,url,**kwargs)
or requests.get()
a. 安装
#在cmd命令行中执行该语句
pip install requests
b. 使用
#在xxx.py脚本中使用
import requests
c. 相关方法(method)
方法 | 描述 |
---|---|
requests.get() | 获取get请求 |
requests.head() | 获取html头部信息 |
requests.post() | 获取post请求 |
requests.put() | 获取put请求 |
requests.patch() | 获取patch请求 |
requests.delete() | 获取delete请求 |
d. Get请求方法
①解释
②语法
requests.get(url,params,**kwargs)
- url:要爬取页面的url链接
- params:url中的额外参数,字典或字节流形式
- **kwargs:其他控制访问的参数
③属性
属性 | 描述 |
---|---|
response.url | 打印请求url |
response.text | 以文本形式打印网页源码 |
response.content | 以字节流形式打印 |
response.headers | 打印头信息 |
response.cookies | 打印Cookie信息 |
response.status_code | 打印状态码 |
e. Post请求方法
①语法
response = requests.post(url,data=None,json=None,**kwargs)
- data:请求所携带参数,必须是字典
- json:所携带json数据格式的数据
②属性
属性名 | 描述 |
---|---|
response.url | 返回请求的URL |
response.text | 返回一个unicode型的字符串类型 |
response.content | 返回一个bytes型的二进制数据 |
response.headers | 返回响应头信息 |
response.cookies | 返回cookies信息 |
response.request | 返回请求相关信息,为一个request对象 |
response.history | 返回请求历史response.status_code返回状态码 |
response.json() | 返回一个字典 |
(3). bs4模块
a. 特性
- 专门解析****html\xml格式
- 自动转化为Unicode编码处理,并输出为****utf-8的编码
- **支持HTML解析器,还支持第三方模块(**lxml)
b. 安装
#cmd命令行
#1.安装bs4模块
pip install bs4
#2.安装lxml解析器
pip install lxml
#3.安装html5lib模块
pip install html5lib
c. 解析器
解析器 | 使用方法 |
---|---|
Python标准库 | BeautifulSoup(markup,"html.parser") |
lxml HTML解析器 | BeautifulSoup(markup,"lxml") |
xml HTML解析器 | BeautifulSoup(markup,"xml") BeautifulSoup(markup,["lxml","xml"]) |
html5lib | BeautifulSoup(markup,"html5lib") |
d. 对象种类
①Tag
-
指html或xml中的标签,BeautifulSoup会****根据指定标签自动寻找
from bs4 import BeautifulSoup soup = BeautifulSoup('<p class="text">这是一段文本内容</p>') tag = soup.p print(type(tag))
②BeautifulSoup
-
表示一个****文档的全部内容,是一个特殊的Tag对象
from bs4 import BeautifulSoup soup = BeautifulSoup('<p class="text">这是一段文本内容</p>') print(soup.name)
③NavigableString
-
表示可遍历字符串,包括****标签内包括的字符串,也就是我们爬取的目标
from bs4 import BeautifulSoup soup = BeautifulSoup('<p class="text">这是一段文本内容</p>') tag = soup.p print(tag.string)
④Comment
-
可以****进一步爬取标签内的注释内容,是特殊的NavigableString对象
from bs4 import BeautifulSoup soup = BeautifulSoup('<p class="text"><!--这里面的是被注释掉的内容-->这是一段文本内容</p>') comment = soup.p.string if type(comment) == bs4.element.Comment: #判断是否为注释内容再输出 print(comment)
e. 使用流程
#py脚本中
from bs4 import BeautifulSoup
①创建对象
- 第二个参数****为空,则代表根据当前系统安装的库,自动选择解析器(lxml>html5lib>Python标准库)
- 传入字符串,打开网络文件
soup = BeautifulSoup(html_doc,'lxml')
- 传入句柄,打开本地文件
soup = BeautifulSoup(open("index.html"),'lxml')
②调用方法
方法 | 含义or实例 |
---|---|
soup.prettify() | 格式化网页代码,方便阅读 |
soup.title | 获取 <title> |
soup.title.string | 获取 <title> 标签的文本内容 |
soup.p | 获取 <p> 标签 |
soup.p["class"] | 获取 <p> 标签的class属性 |
soup.find('a') | 返回第一个 <a> 标签 |
soup.find_all('a') | 返回所有的 <a> 标签 |
soup.select('a') soup.select('.class-name') soup.select('#id-name') soup.select('div p') soup.select('a[href="link.html"]') | 选择特定的标签 选择特定的类元素 选择特定的id元素 选择某个父元素下的子元素 选择具有特性属性值的方法 |
③进一步进行数据清洗
**## **