urllib是Python中內置的發送網絡請求的一個庫(包),在Python2中由urllib和urllib2兩個庫來實現請求的發送,可是在Python中已經不存在urllib2這個庫了,已經將urllib和urllib2合併爲urllib。
urllib是一個庫(包),request是urllib庫裏面用於發送網絡請求的一個模塊json
1.發送一個不攜帶參數的get請求api
import urllib.request #發起一個不攜帶參數的get請求 response=urllib.request.urlopen('http://www.baidu.com') print(response.reason) #調用status屬性能夠這次請求響應的狀態碼,200表示這次請求成功 print(response.status) #調用url屬性,能夠獲取這次請求的地址 print(response.url) print(response.headers) #因爲使用read方法拿到的響應的數據是二進制數據,全部須要使用decode解碼成utf-8編碼 # print(response.read().decode('utf-8'))
2.發送一個攜帶參數的get請求網絡
import urllib.request import urllib.parse #http://www.yundama.com/index/login?username=1313131&password=132213213&utype=1&vcode=2132312 # 定義出基礎網址 base_url='http://www.yundama.com/index/login' #構造一個字典參數 data_dict={ "username":"1313131", "password":"13221321", "utype":"1", "vcode":"2132312" } # 使用urlencode這個方法將字典序列化成字符串,最後和基礎網址進行拼接 data_string=urllib.parse.urlencode(data_dict) print(data_string) new_url=base_url+"?"+data_string response=urllib.request.urlopen(new_url) print(response.read().decode('utf-8'))
3.構造一個攜帶參數的POST請求函數
import urllib.request import urllib.parse #測試網址:http://httpbin.org/post #定義一個字典參數 data_dict={"username":"zhangsan","password":"123456"} #使用urlencode將字典參數序列化成字符串 data_string=urllib.parse.urlencode(data_dict) #將序列化後的字符串轉換成二進制數據,由於post請求攜帶的是二進制參數 last_data=bytes(data_string,encoding='utf-8') #若是給urlopen這個函數傳遞了data這個參數,那麼它的請求方式則不是get請求,而是post請求 response=urllib.request.urlopen("http://httpbin.org/post",data=last_data) #咱們的參數出如今form表單中,這代表是模擬了表單的提交方式,以post方式傳輸數據 print(response.read().decode('utf-8'))
4.補充:post
若是直接將中文傳入URL中請求,會致使編碼錯誤。咱們須要使用quote() ,對該中文關鍵字進行URL編碼測試
import urllib.request city=urllib.request.quote('鄭州市'.encode('utf-8')) response=urllib.request.urlopen('http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'.format(city)) print(response.read().decode('utf-8'))