python:urllib:HTTPResponse對象的用法


不管是使用urllib.request.urlopen()方法,還是使用opener.open()方法,都返回同樣類型的HTTPResponse對象,用法總結如下:

# !/usr/bin/env python
# -*- coding:utf-8 -*-
 
from urllib import request
from urllib import response
 
URL="http://www.baidu.com/"
 
# 構造請求頭信息
# 反反爬蟲:設置User-Agent
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))   # <class 'http.client.HTTPResponse'>
# 獲取HTTP協議版本號(10 for HTTP/1.0, 11 for HTTP/1.1)
print(resp.version)
 
# 獲取響應碼
print(resp.status)
print(resp.getcode())
 
# 獲取響應描述字符串
print(resp.reason)
 
# 獲取實際請求的頁面url(防止重定向用)
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'))

 

 

轉自:https://blog.csdn.net/topleeyap/article/details/78845946


免責聲明!

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



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