urllib提供了一系列用于操作URL的功能。
Get
urllib的request 模塊可以非常方便地抓取URL內(nèi)容,也就是發(fā)送一個GET請求到指定的頁面,然后返回HTTP的響應(yīng):
例如,對豆瓣的一個URLhttps://api.douban.com/v2/book/2129650 進(jìn)行抓取,,并返回響應(yīng):
from urllib import request
with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
data = f.read()
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', data.decode('utf-8'))
可以看到HTTP響應(yīng)的頭和JSON數(shù)據(jù):
Status: 200 OK
Server: nginx
Date: Tue, 26 May 2015 10:02:27 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2049
Connection: close
Expires: Sun, 1 Jan 2006 01:00:00 GMT
Pragma: no-cache
Cache-Control: must-revalidate, no-cache, private
X-DAE-Node: pidl1
Data: {"rating":{"max":10,"numRaters":16,"average":"7.4","min":0},"subtitle":"","author":["廖雪峰編著"],"pubdate":"2007-6",...}
如果我們要想模擬瀏覽器發(fā)送GET請求,,就需要使用Request 對象,,通過往Request 對象添加HTTP頭,,我們就可以把請求偽裝成瀏覽器,。例如,模擬iPhone 6去請求豆瓣首頁:
from urllib import request
req = request.Request('http://www.douban.com/')
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 request.urlopen(req) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))
這樣豆瓣會返回適合iPhone的移動版網(wǎng)頁:
...
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="format-detection" content="telephone=no">
<link rel="apple-touch-icon" sizes="57x57" />
...
Post
如果要以POST發(fā)送一個請求,,只需要把參數(shù)data 以bytes形式傳入,。
我們模擬一個微博登錄,先讀取登錄的郵箱和口令,,然后按照weibo.cn的登錄頁的格式以username=xxx&password=xxx 的編碼傳入:
from urllib import request, parse
print('Login to weibo.cn...')
email = input('Email: ')
passwd = input('Password: ')
login_data = parse.urlencode([
('username', email),
('password', passwd),
('entry', 'mweibo'),
('client_id', ''),
('savestate', '1'),
('ec', ''),
('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
])
req = request.Request('https://passport.weibo.cn/sso/login')
req.add_header('Origin', 'https://passport.weibo.cn')
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')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
with request.urlopen(req, data=login_data.encode('utf-8')) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))
如果登錄成功,,我們獲得的響應(yīng)如下:
Status: 200 OK
Server: nginx/1.2.0
...
Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn
...
Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}
如果登錄失敗,我們獲得的響應(yīng)如下:
...
Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"[email protected]","errline":536}}
Handler
如果還需要更復(fù)雜的控制,,比如通過一個Proxy去訪問網(wǎng)站,,我們需要利用ProxyHandler 來處理,示例代碼如下:
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open('http://www./login.html') as f:
pass
小結(jié)
urllib提供的功能就是利用程序去執(zhí)行各種HTTP請求,。如果要模擬瀏覽器完成特定功能,,需要把請求偽裝成瀏覽器。偽裝的方法是先監(jiān)控瀏覽器發(fā)出的請求,,再根據(jù)瀏覽器的請求頭來偽裝,,User-Agent 頭就是用來標(biāo)識瀏覽器的。
練習(xí)
利用urllib讀取JSON,,然后將JSON解析為Python對象:
參考源碼
use_urllib.py
|