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模塊中最常用的函數爲urllib.request.urlopen()

urllib.request.urlopen函數參數如下:

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  需要打開的網址

-         data:Post提交的數據

-         timeout:設置網站的訪問超時時間

urlopen返回對象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :對HTTPResponse類型數據進行操作

-         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的狀態。



Python官網request庫鏈接





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章