美文网首页
Python 常用第三方模块

Python 常用第三方模块

作者: _YZG_ | 来源:发表于2018-01-05 17:55 被阅读75次

一、Pillow

官方文档
https://pillow.readthedocs.org/

缩放
from PIL import Image

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')
# 获得图像尺寸:
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 缩放到50%:
im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
# 把缩放后的图像用jpeg格式保存:
im.save('thumbnail.jpg', 'jpeg')


模糊
from PIL import Image, ImageFilter

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')
# 应用模糊滤镜:
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')
image

验证码
from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random

# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
code.jpg

二、requests

GET
>>> import requests
>>> r = requests.get('https://www.douban.com/') # 豆瓣首页
>>> r.status_code
200
>>> r.text
r.text
'<!DOC...


带参数的URL,传入dict作为params参数
>>> r = requests.get('https://www.douban.com/search', params={'q': 'python', 'cat': '1001'})
>>> r.url # 实际请求的URL
'https://www.douban.com/search?q=python&cat=1001'

自动检测编码
>>> r.encoding
'utf-8'

无论响应是文本还是二进制内容,我们都可以用content属性获得bytes对象:
>>> r.content
b'<!DOCTYPE html>\n<。。。


对于特定类型的响应,例如JSON,可以直接获取
>>> r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json')
>>> r.json()
{'query': {'count': 1, 'created': '2017-11-17T07:14:12Z', ...


需要传入HTTP Header时,我们传入一个dict作为headers参数
>>> r = requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})
>>> r.text
<!DOCTYPE html>。。。
POST

要发送POST请求,只需要把get()方法变成post(),然后传入data参数作为POST请求的数据


>>> r = requests.post('https://accounts.douban.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'})

requests默认使用application/x-www-form-urlencoded对POST数据编码。如果要传递JSON数据,可以直接传入json参数:

params = {'key': 'value'}
r = requests.post(url, json=params) # 内部自动序列化为JSON

上传文件
>>> upload_files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=upload_files)

在读取文件时,注意务必使用'rb'即二进制模式读取,这样获取的bytes长度才是文件的长度。

把post()方法替换为put(),delete()等,就可以以PUT或DELETE方式请求资源。

获取请求头
>>> r.headers
{Content-Type...


cookie
>>> r.cookies['ts']
'example_cookie_123。。。'

要在请求中传入Cookie,只需准备一个dict传入cookies参数:

>>> cs = {'token': '12345', 'status': 'working')
>>> r = requests.get(url, cookies=cs)


传入以秒为单位的timeout参数:

>>> r = requests.get(url, timeout=2.5) # 2.5秒后超时

三、chardet

官方文档
https://chardet.readthedocs.io/en/latest/supported-encodings.html

>>> import chardet
>>> chardet.detect(b'Hello, world!')
{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
检测出的编码是ascii,注意到还有个confidence字段,表示检测的概率是1.0(即100%)。


>>> data = '离离原上草,一岁一枯荣'.encode('gbk')
>>> chardet.detect(data)
{'encoding': 'GB2312', 'confidence': 0.7407407407407407, 'language': 'Chinese'}


获取到编码后,再转换为str,就可以方便后续处理

四、psutil

官网地址
https://github.com/giampaolo/psutil

获取CPU信息、获取内存信息、获取磁盘信息、获取网络信息、获取进程信息等等。。

例:获取CPU信息
>>> import psutil
>>> psutil.cpu_count() # CPU逻辑数量
4
>>> psutil.cpu_count(logical=False) # CPU物理核心
2
# 2说明是双核超线程, 4则是4核非超线程

相关文章

  • Python常用模块

    Python常用模块之time模块 Python常用模块之os模块 Python常用模块之sys模块 Python...

  • 学习计划【2017.11.13-11.30】

    flask框架深入学习理解源代码各种扩展的运用 探索Python的模块内置模块标准库第三方常用库结合Python源...

  • Python使用ORM进行数据库操作&原生SQL查询

    sqlalchemy是python最为常用的第三方ORM模块。1、pycharm安装sqlalchemy命令: p...

  • 测试面试问题记录

    1.前端代码如何区分是CSS还是js 2.常用xpath定位方法 3.Python常用第三方模块 4.HTTP请求...

  • python相关模块

    1 sklearn简介 sklearn是机器学习中一个常用的python第三方模块,网址:http://sciki...

  • SSH | Python ssh远程服务器的简单使用

    Python ssh模块 python有很多第三方的SSh模块,我们也可以使用python自带的ssh模块,进行一...

  • Anaconda

    集成了python及其常用包,并做了版本管理。Anaconda安装的第三方模块会安装在Anaconda自己的路径下...

  • Python OS模块常用方法总结

    Python OS模块常用方法总结Python OS模块方法:操作 说明os.g...

  • 1-text模块

    概述 str 无疑是python最常用的字符串处理模块,除此之外还有一些补充 str 功能的第三方模块比如 str...

  • python之模块之碎碎念

    import语句导入的模块顺序 1、Python标准库模块 2、python第三方库模块 3、应用程序自定义模块 ...

网友评论

      本文标题:Python 常用第三方模块

      本文链接:https://www.haomeiwen.com/subject/gzdsnxtx.html