urllib提供了一系列用於操做URL的功能。javascript
urllib的request
模塊能夠很是方便地抓取URL內容,也就是發送一個GET請求到指定的頁面,而後返回HTTP的響應:html
例如,對豆瓣的一個URLhttps://api.douban.com/v2/book/2129650
進行抓取,並返回響應:java
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響應的頭和JSON數據:python
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","tags":[{"count":20,"name":"spring","title":"spring"}...}
若是咱們要想模擬瀏覽器發送GET請求,就須要使用Request
對象,經過往Request
對象添加HTTP頭,咱們就能夠把請求假裝成瀏覽器。例如,模擬iPhone 6去請求豆瓣首頁:nginx
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的移動版網頁:spring
...
<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" href="http://img4.douban.com/pics/cardkit/launcher/57.png" /> ...
若是要以POST發送一個請求,只須要把參數data
以bytes形式傳入。sql
咱們模擬一個微博登陸,先讀取登陸的郵箱和口令,而後按照weibo.cn的登陸頁的格式以username=xxx&password=xxx
的編碼傳入:json
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'))
若是登陸成功,咱們得到的響應以下:api
Status: 200 OK
Server: nginx/1.2.0
...
Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn ... Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}
若是登陸失敗,咱們得到的響應以下:瀏覽器
... Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"example@python.org","errline":536}}
若是還須要更復雜的控制,好比經過一個Proxy去訪問網站,咱們須要利用ProxyHandler
來處理,示例代碼以下:
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com: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.example.com/login.html') as f: pass
urllib提供的功能就是利用程序去執行各類HTTP請求。若是要模擬瀏覽器完成特定功能,須要把請求假裝成瀏覽器。假裝的方法是先監控瀏覽器發出的請求,再根據瀏覽器的請求頭來假裝,User-Agent
頭就是用來標識瀏覽器的。