1. 程式人生 > >python學習筆記:網路請求——urllib模組

python學習筆記:網路請求——urllib模組

python操作網路,也就是開啟一個網站,或者請求一個http介面,可以使用urllib模組。
urllib模組是一個標準模組,直接import urllib即可,在python3裡面只有urllib模組,在python2裡面有urllib模組和urllib2模組

 

Urllib是python內建的HTTP請求庫
包括以下模組
urllib.request 請求模組
urllib.error 異常處理模組
urllib.parse url解析模組
urllib.robotparser robots.txt解析模組

 

因為有更好用的模組,所以再在此不對此模組進行更多解釋,想更好的學習urllib模組可以參考下面的部落格或官方文件。

參考部落格:http://www.cnblogs.com/zhaof/p/6910871.html

官方文件:https://docs.python.org/3/library/urllib.html

import json
from urllib.request import urlopen # 開啟網頁
from urllib.parse import urlencode

# ====get請求====
url='https://www.cnblogs.com/haifeima/p/9829601.html#autoid-5-0-5'
res=urlopen(url).read()#發起get請求,並獲取結果
print(res.decode())#返回的是二進位制型別,所以要decode變成字串 f=open('b.html','w',encoding='utf-8') #將上面的網頁儲存到本地,執行後會在本地生成一個叫做b.html的檔案 f.write(res.decode()) f.close() # ====post請求==== url='http://api.nnzhp.cn/api/user/login' data={"username":"niuhanyang","passws":"aA123456"} data=urlencode(data) res=urlopen(url,data).read()#
發起post請求,加個date把資料傳進來,獲取結果 print(res.decode())#轉成decode格式 d=json.loads(res.decode())#轉成字典 print(d.get('login_info').get('sign')) f=open('b.html','w',encoding='utf-8') #將上面的網頁儲存到本地,執行後會在本地生成一個叫做b.html的檔案 f.write(res.decode()) f.close()