本文將介紹python里常用的模塊。如未特殊說明,所有示例均以python3.4為例:
$ python -V
Python 3.4.3
網絡請求
urllib
urllib提供了一系列用於操作URL的功能。通過urllib我們可以很方便的抓取網頁內容。
抓取網頁內容
# coding: utf-8
import urllib.request
url = 'https://api.douban.com/v2/book/2129650'
with urllib.request.urlopen(url) as f:
headers = f.getheaders() # 報文頭部
body = f.read() # 報文內容
print(f.status, f.reason) # 打印狀態碼、原因語句
for k,v in headers:
print(k + ': ' + v)
print(body.decode('utf-8'))
抓取百度搜索圖片
import urllib.request
import os
import re
import time
url=r'http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1488722322213_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%A3%81%E7%BA%B8%E5%B0%8F%E6%B8%85%E6%96%B0&f=3&oq=bizhi%E5%B0%8F%E6%B8%85%E6%96%B0&rsp=0'
imgPath=r'E:\img'
if not os.path.isdir(imgPath):
os.mkdir(imgPath)
imgHtml=urllib.request.urlopen(url).read().decode('utf-8')
#test html
#print(imgHtml)
urls=re.findall(r'"objURL":"(.*?)"',imgHtml)
index=1
for url in urls:
print("下載:",url)
#未能正確獲得網頁 就進行異常處理
try:
res=urllib.request.urlopen(url)
if str(res.status)!='200':
print('未下載成功:',url)
continue
except Exception as e:
print('未下載成功:',url)
filename=os.path.join(imgPath,str(time.time()) + '_' + str(index)+'.jpg')
with open(filename,'wb') as f:
f.write(res.read())
print('下載完成\n')
index+=1
print("下載結束,一共下載了 %s 張圖片"% (index-1))
python2.7的用戶需要把urllib.request
替換成urllib
。
批量下載圖片
# coding: utf-8
import os,urllib.request
url_path = 'http://www.ruanyifeng.com/images_pub/'
imgPath=r'E:\img'
if not os.path.isdir(imgPath):
os.mkdir(imgPath)
index=1
for i in range(1,355):
url = url_path + 'pub_' + str(i) + '.jpg'
print("下載:",url)
try:
res = urllib.request.urlopen(url)
if(str(res.status) != '200'):
print("下載失敗:", url)
continue
except:
print('未下載成功:',url)
filename=os.path.join(imgPath,str(i)+'.jpg')
with open(filename,'wb') as f:
f.write(res.read())
print('下載完成\n')
index+=1
print("下載結束,一共下載了 %s 張圖片"% (index-1))
模擬GET請求附帶頭信息
urllib.request.Request
實例化后有個add_header()
方法可以添加頭信息。
# coding: utf-8
import urllib.request
url = 'http://www.douban.com/'
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with urllib.request.urlopen(req) as f:
headers = f.getheaders()
body = f.read()
print(f.status, f.reason)
for k,v in headers:
print(k + ': ' + v)
print(body.decode('utf-8'))
這樣會返回適合iPhone的移動版網頁。
發送POST請求
urllib.request.urlopen()
第二個參數可以傳入需要post的數據。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from urllib import request
from urllib.parse import urlencode
#----------------------------------
# 手機號碼歸屬地調用示例代碼 - 聚合數據
# 在線接口文檔:http://www.juhe.cn/docs/11
#----------------------------------
def main():
#配置您申請的APPKey
appkey = "*********************"
#1.手機歸屬地查詢
request1(appkey,"GET")
#手機歸屬地查詢
def request1(appkey, m="GET"):
url = "http://apis.juhe.cn/mobile/get"
params = {
"phone" : "", #需要查詢的手機號碼或手機號碼前7位
"key" : appkey, #應用APPKEY(應用詳細頁查詢)
"dtype" : "", #返回數據的格式,xml或json,默認json
}
params = urlencode(params).encode('utf-8')
if m =="GET":
f = request.urlopen("%s?%s" % (url, params))
else:
f = request.urlopen(url, params)
content = f.read()
res = json.loads(content.decode('utf-8'))
if res:
error_code = res["error_code"]
if error_code == 0:
#成功請求
print(res["result"])
else:
print("%s:%s" % (res["error_code"],res["reason"]) )
else:
print("request api error")
if __name__ == '__main__':
main()
Requests
雖然Python的標准庫中urllib2
模塊已經包含了平常我們使用的大多數功能,但是它的API使用起來讓人實在感覺不好。它已經不適合現在的時代,不適合現代的互聯網了。而Requests
的誕生讓我們有了更好的選擇。
正像它的名稱所說的,HTTP for Humans
,給人類使用的HTTP庫!在Python的世界中,一切都應該簡單。Requests
使用的是urllib3
,擁有了它的所有特性,Requests
支持 HTTP 連接保持和連接池,支持使用 cookie 保持會話,支持文件上傳,支持自動確定響應內容的編碼,支持國際化的 URL 和 POST 數據自動編碼。現代、國際化、人性化。
官網:http://python-requests.org/
文檔:http://cn.python-requests.org/zh_CN/latest/
Github主頁:https://github.com/kennethreitz/requests
需要先安裝:
$ pip3 install requests
Collecting requests
Downloading requests-2.13.0-py2.py3-none-any.whl (584kB)
100% |████████████████████████████████| 593kB 455kB/s
Installing collected packages: requests
Successfully installed requests-2.13.0
請求示例
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
url = 'https://api.github.com/user'
# r = requests.request('get', url, auth=('52fhy', ''))
r = requests.get(url, auth=('', ''))
print('Status: %s' % r.status_code) # 狀態碼
# 頭信息
for k,v in r.headers.items():
print(k + ': ' + v)
print('encoding: ' , r.encoding)
print('body: ' , r.text)
print('json body: ' , r.json())
默認情況下,dict迭代的是key。如果要迭代value,可以用
for value in d.values()
,如果要同時迭代key和value,可以用for k, v in d.items()
。
POST請求
基於表單的:
# coding: utf-8
import requests
payload = {'name': 'python', 'age': '11'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
基於text的:
# coding: utf-8
import requests,json
payload = {'name': 'python', 'age': '11'}
r = requests.post("https://api.github.com/some/endpoint", data=json.dumps(payload))
print(r.text)
還可以使用 json 參數直接傳遞,然后它就會被自動編碼。這是 2.4.2 版的新加功能:
r = requests.post("https://api.github.com/some/endpoint", json=payload)
hashlib
md5
import hashlib
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
print(md5.hexdigest())
結果如下:
d26a53750bc40b38b65a520292f69306
update()
,用於將內容分塊進行處理,適用於大文件的情況。示例:
import hashlib
def get_file_md5(f):
m = hashlib.md5()
while True:
data = f.read(10240)
if not data:
break
m.update(data)
return m.hexdigest()
with open(YOUR_FILE, 'rb') as f:
file_md5 = get_file_md5(f)
對於普通字符串的md5,可以封裝成函數:
def md5(string):
import hashlib
return hashlib.md5(string.encode('utf-8')).hexdigest()
SHA1
import hashlib
sha1 = hashlib.sha1()
sha1.update('py'.encode('utf-8'))
sha1.update('thon'.encode('utf-8'))
print(sha1.hexdigest())
等效於:
hashlib.sha1('python'.encode('utf-8')).hexdigest()
SHA1的結果是160 bit字節,通常用一個40位的16進制字符串表示。
此外,hashlib還支持sha224
, sha256
, sha384
, sha512
。
base64
Base64是一種用64個字符來表示任意二進制數據的方法。Python內置的base64可以直接進行base64的編解碼:
>>> import base64
>>> base64.b64encode(b'123')
b'MTIz'
>>> base64.b64decode(b'MTIz')
b'123'
由於標准的Base64編碼后可能出現字符+
和/
,在URL中就不能直接作為參數,所以又有一種"url safe"的base64編碼,其實就是把字符+
和/
分別變成-
和_
:
>>> base64.b64encode(b'i\xb7\x1d\xfb\xef\xff')
b'abcd++//'
>>> base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff')
b'abcd--__'
>>> base64.urlsafe_b64decode('abcd--__')
b'i\xb7\x1d\xfb\xef\xff'
時間日期
該部分在前面的筆記里已做詳細介紹:http://www.cnblogs.com/52fhy/p/6372194.html。本節僅作簡單回顧。
time
# coding:utf-8
import time
# 獲取時間戳
timestamp = time.time()
print(timestamp)
# 格式時間
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 返回當地時間下的時間元組t
print(time.localtime())
# 將時間元組轉換為時間戳
print(time.mktime(time.localtime()))
t = (2017, 2, 11, 15, 3, 38, 1, 48, 0)
print(time.mktime(t))
# 字符串轉時間元組:注意時間字符串與格式化字符串位置一一對應
print(time.strptime('2017 02 11', '%Y %m %d'))
# 睡眠
print('sleeping...')
time.sleep(2) # 睡眠2s
print('sleeping end.')
輸出:
1486797515.78742
2017-02-11 15:18:35
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=11, tm_hour=15, tm_min=18, tm_sec=35, tm_wday=5, tm_yday=42, tm_isdst=0)
1486797515.0
1486796618.0
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=42, tm_isdst=-1)
sleeping...
sleeping end.
datetime
方法概覽:
datetime.now() # 當前時間,datetime類型
datetime.timestamp() # 時間戳,浮點類型
datetime.strftime('%Y-%m-%d %H:%M:%S') # 格式化日期對象datetime,字符串類型
datetime.strptime('2017-2-6 23:22:13', '%Y-%m-%d %H:%M:%S') # 字符串轉日期對象
datetime.fromtimestamp(ts) # 獲取本地時間,datetime類型
datetime.utcfromtimestamp(ts) # 獲取UTC時間,datetime類型
示例:
# coding: utf-8
from datetime import datetime
import time
now = datetime.now()
print(now)
# datetime模塊提供
print(now.timestamp())
輸出:
2017-02-06 23:26:54.631582
1486394814.631582
小數位表示毫秒數。
圖片處理
PIL
PIL(Python Imaging Library)已經是Python平台事實上的圖像處理標准庫了。PIL功能非常強大,但API卻非常簡單易用。
安裝:
$ pip install Pillow
Collecting Pillow
Downloading Pillow-4.0.0-cp34-cp34m-win32.whl (1.2MB)
Successfully installed Pillow-4.0.0
圖像縮放:
# coding: utf-8
from PIL import Image
im = Image.open('test.jpg')
print(im.format, im.size, im.mode)
im.thumbnail((200, 100))
im.save('thumb.jpg', 'JPEG')
模糊效果:
# coding: utf-8
from PIL import Image,ImageFilter
im = Image.open('test.jpg')
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')
驗證碼:
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')
注意示例里的字體文件必須是絕對路徑。
下載
you-get
安卓you-get
pin install you-get
需要有ffmpeg的支持。windows下載地址:
https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-3.4.1-win64-static.zip
解壓后添加環境變量,例如:
C:\Program Files\ffmpeg-3.4.1-win64-static\bin
然后就可以下載各大視頻網站的視頻了。示例:
you-get v.youku.com/v_show/id_XNTA5MDQ1OTM2.html
如果提示201:客戶端未授權,可以安裝Adobe Flash Player 28 PPAPI試試。
如果你在使用Mac,可以下載客戶端:
https://github.com/coslyk/moonplayer
參考:
1、Python資源
http://hao.jobbole.com/?catid=144