Python 3.6模組學習urllib的urllib.request.urlopen()函式學習
urllib提供了一系列用於操作URL的功能。包含urllib.request,urllib.error,urllib.parse,urllib.robotparser四個子模組。
官網資料如下:
urllib
is
a package that collects several modules for working with URLs:
- urllib.request開啟和瀏覽url中內容
- urllib.error包含從 urllib.request發生的錯誤或異常
- urllib.parse解析url
- urllib.robotparser解析 robots.txt檔案
urllib.request.
urlopen()
urllib.request.
urlopen函式引數如下:
urllib.request.
urlopen
(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
- url: 需要開啟的網址
- data:Post提交的資料
- timeout:設定網站的訪問超時時間
urlopen返回物件提供方法:
- read() , readline() ,readlines() , fileno() , close() :對
- info():返回HTTPMessage物件,表示遠端伺服器返回的頭資訊
- getcode():返回Http狀態碼。如果是http請求,200請求成功完成 ; 404網址未找到
- geturl():返回請求的url
Get
urllib的request
模組可以非常方便地抓取URL內容,當data引數為空的時候也就是傳送一個GET請求到指定的頁面,然後返回HTTP的響應:
例如對百度的一個URLhttps://www.baidu.com/
進行抓取,並返回響應:
執行程式可以得到如下:from urllib import request with request.urlopen('https://www.baidu.com/') as f: data = f.read() print('Status:', f.status, f.reason) print('Data:', data)
Status: 200 OK
Data: b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>
這時我們發現Data內容與網頁內容有幾分差異
Data的資料格式為bytes型別,需要decode()解碼,轉換成str型別。
print('Data:', data.decode('utf-8'))
把得到的Data變為 utf-8編碼形式,變化後如下:Data: <html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
這樣得到的內容就可以與網頁編碼內容一樣了
Post
如果要以POST傳送一個請求,
urllib.request.urlopen(url,data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
urlopen()的data引數預設為None,當data引數不為空的時候,urlopen()提交方式為Post。
Post的資料必須是bytes或者iterable of bytes,不能是str,如果是str需要進行encode()編碼
使用Request包裝請求
urllib.request.
Request
(url, data=None, headers={},
method=None)
使用request()來包裝請求,再通過urlopen()獲取頁面。
url= r'http://www.xxxxxxxxxxxxxxxx.com'
headers = {
'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
'Referer': r'http://www.xxxxxxxxxxxxxxxx.com',
'Connection': 'keep-alive'
}
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
- User-Agent :這個頭部可以攜帶如下幾條資訊:瀏覽器名和版本號、作業系統名和版本號、預設語言
- Referer:可以用來防止盜鏈,有一些網站圖片顯示來源http://***.com,就是檢查Referer來鑑定的
- Connection:表示連線狀態,記錄Session的狀態。