urllib库进行网络请求后返回的HTTPResponse对象的用法总结
本文转自「已注销」 并作补充
不管是使用urllib.request.urlopen()方法,还是使用opener.open()方法,都返回同样类型的HTTPResponse对象,用法总结如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
from urllib import request from urllib import response URL="http://www.baidu.com/"
request_headers={ "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" }
req=request.Request(URL,headers=request_headers)
resp=request.urlopen(req) print(type(resp))
print(resp.version)
print(resp.status) print(resp.getcode())
print(resp.reason)
print(resp.geturl())
print(resp.getheader(name="Content-Type"))
print(resp.getheaders())
print(resp.info())
print(resp.readline().decode('utf-8')) print(resp.read().decode('utf-8'))
|