urllib庫發送get和post請求


urllib是Python中內置的發送網絡請求的一個庫(包),在Python2中由urllib和urllib2兩個庫來實現請求的發送,但是在Python中已經不存在urllib2這個庫了,已經將urllib和urllib2合並為urllib。
urllib是一個庫(包),request是urllib庫里面用於發送網絡請求的一個模塊

1.發送一個不攜帶參數的get請求

 

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.補充:

如果直接將中文傳入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'))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM