使用urllib
urlopen的基本用法:
工具為:python3(windows)
其完整表達式為:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
1、發(fā)出一個請求.打開bttpbin.org網頁,此處為get方式的請求類型>>>import urllib.request?
>>>?response = urllib.request.urlopen("http://httpbin.org")
#此處為將 結果賦值給response
>>> print(response.read().decode('utf-8'))
#得到的response是bytes類型,所以我們需要使用decode
httpbin.org:可以以后用來做http測試2、此處為POST 類型的請求需要使用到data
>>> import urllib.parse
>>> import urllib.request
>>> data = bytes(urllib.parse.urlencode({"word":"hello"}),encoding="utf8")
#需要創(chuàng)建data參數,需要為bytes類型,用urlencode將字典傳過去
>>> response = urllib.request.urlopen("http://httpbin.org/post",data = data)
>>> print(response.read())
?
3、超時設置timeout>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org/get",timeout=1 )
>>> print(response.read())
發(fā)現下方有正常的響應
?
?若超時的時間為0.1,如果出現異常,對異常進行捕獲
>>> import socket
>>> import urllib.request
>>> import urllib.error
try:
response = urllib.request.urlopen("http://httpbin.org/get",timeout=0.1)
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print("TIME OUT")
會出現TIME? OUT 結果。
發(fā)送請求之后出現響應1、響應類型
>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org")
>>> print(type(response))
<class 'http.client.HTTPResponse'>
>>> import urllib.request
>>> response =urllib.request.urlopen("http://httpbin.org")
>>> print(response.status)? ?#此處為狀態(tài)碼,200顯示為成功的意思
200
>>> print(response.getheaders()) #此處為獲取所有的狀態(tài)頭,并且以元組的形式輸出
[('Connection', 'close'), ('Server', 'gunicorn/19.9.0'), ('Date', 'Tue, 09 Oct 2018 12:49:34 GMT'), ('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '10122'), ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Credentials', 'true'), ('Via', '1.1 vegur')]
>>> print(response.getheader('Server'))
gunicorn/19.9.0
response.read():獲取響應體內容為bytes類型,我們可以用decode進行轉化
>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org")
>>> print(response.read().decode('utf-8'))
?
Request的基本用法
(如果我們想要發(fā)送header對象或者其他復雜東西,就需要用到Request)
>>> import urllib.request
>>> response = urllib.request.Request("http://httpbin.org")
>>> response = urllib.request.urlopen(request)
>>> print(response.read().decode('utf-8'))
正常輸出,與上方直接輸入的結果是完全一致,有了Request能夠更加方便
from urllib import request,parse
url = "http://httpbin.org/post"
headers = {
"User-Agent":'Mozllia/4.0(compatible;MSIE 5.5;Windows NT)',
"Host":'httpbin.org'
}
dict = {
'name':'Germey'
}
data = bytes(parse.urlencode(dict),encoding="utf8")
req = request.Request(url=url,data=data,headers=headers,method="POST")
response= request.urlopen(req)
print(response.read().decode("utf-8"))
?
轉載于:https://www.cnblogs.com/zz-1021/p/9762921.html
總結
- 上一篇: 【洛谷 T47488】 D:希望 (点分
- 下一篇: “理想智造”品牌首次面世 新造车势力车和