使用urllib
urlopen的基本用法:
工具為:python3(windows)
其完整表達(dá)式為:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
1、發(fā)出一個請求.打開bttpbin.org網(wǎng)頁,此處為get方式的請求類型>>>import urllib.request?
>>>?response = urllib.request.urlopen("http://httpbin.org")
#此處為將 結(jié)果賦值給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參數(shù),需要為bytes類型,用urlencode將字典傳過去
>>> response = urllib.request.urlopen("http://httpbin.org/post",data = data)
>>> print(response.read())
?
3、超時設(shè)置timeout>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org/get",timeout=1 )
>>> print(response.read())
發(fā)現(xiàn)下方有正常的響應(yīng)
?
?若超時的時間為0.1,如果出現(xiàn)異常,對異常進(jìn)行捕獲
>>> 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")
會出現(xiàn)TIME? OUT 結(jié)果。
發(fā)送請求之后出現(xiàn)響應(yīng)1、響應(yīng)類型
>>> 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():獲取響應(yīng)體內(nèi)容為bytes類型,我們可以用decode進(jìn)行轉(zhuǎn)化
>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org")
>>> print(response.read().decode('utf-8'))
?
Request的基本用法
(如果我們想要發(fā)送header對象或者其他復(fù)雜東西,就需要用到Request)
>>> import urllib.request
>>> response = urllib.request.Request("http://httpbin.org")
>>> response = urllib.request.urlopen(request)
>>> print(response.read().decode('utf-8'))
正常輸出,與上方直接輸入的結(jié)果是完全一致,有了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"))
?
轉(zhuǎn)載于:https://www.cnblogs.com/zz-1021/p/9762921.html
總結(jié)
- 上一篇: 【洛谷 T47488】 D:希望 (点分
- 下一篇: TensorFlow 调用预训练好的模型