1. 程式人生 > >python自帶的urllib使用

python自帶的urllib使用

1.urllib中request構建完整請求

"""request構建完整請求"""
from urllib import request


# Request封裝url
req = request.Request("https://python.org")
# 發起請求並儲存請求結果
res = request.urlopen(req)
# 列印響應資訊
print(res.read().decode("utf-8"))


"""
class Request:

    def __init__(self, url, data=None, headers={},
                 origin_req_host=None, unverifiable=False,
                 method=None):
    引數解析:
    url:請求URL
    data:跟urlopen裡面的data傳遞一樣的bytes型別資料
    headers:請求頭可直接構造,也可以使用類方法add_header()傳遞引數
    origin_req_host:請求時的host名稱或者IP
    unverifiable:許可權操作,有或者沒有。預設False,表示使用者沒有許可權選擇接受這個請求的結果
    method:請求時的方法,比如GET,POST,DELETE等
""" from urllib import request, parse # 設定請求的url url = "http://httpbin.org/post" # 設定請求頭資訊 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "Host": "httpbin.org" } dict = {"name": "Germey"} # 把字典轉換成位元組流資訊 data = bytes(parse.urlencode(dict), encoding="
utf8") # 引數按值傳遞 req = request.Request(url=url, data=data, headers=headers, method="POST") # 發起請求並儲存請求結果 res = request.urlopen(req) # 列印響應資訊 print(res.read().decode("utf-8"))
View Code

2.request中urlopen的get請求分析

"""urlopen的get分析"""
from urllib import request
from http.client import HTTPResponse  #
引用 res = request.urlopen("https://www.python.org") print(type(res)) # 列印返回結果的型別,用from引用這個型別檢視具備的方法和屬性 print(res.status) # 返回相應的狀態碼 print(res.getheaders()) # 返回所有請求頭資訊 print(res.getheader("Server")) # 返回伺服器資訊,nginx。socket伺服器中比較牛逼的一種 # def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, # *, cafile=None, capath=None, cadefault=False, context=None): """ 原始碼解釋: 開啟URL url,可以是字串或Request物件。     * data *必須是指定要傳送到的其他資料的物件     伺服器,如果不需要這樣的資料,則為None。請參閱請求     細節。     urllib.request模組使用HTTP / 1.1幷包含“Connection:close”     HTTP請求中的標頭。     可選的* timeout *引數指定超時(以秒為單位)     阻塞操作,如連線嘗試(如果未指定,則     將使用全域性預設超時設定)。這僅適用於HTTP,     HTTPS和FTP連線。     如果指定了* context *,則它必須是描述的ssl.SSLContext例項     各種SSL選項。有關更多詳細資訊,請參閱HTTPSConnection。     可選的* cafile *和* capath *引數指定一組可信CA.     HTTPS請求的證書。 cafile應該指向一個檔案     包含一捆CA證書,而capath應指向a     雜湊證書檔案的目錄。更多資訊可以在中找到     ssl.SSLContext.load_verify_locations()。     * cadefault *引數被忽略。     此函式始終返回可用作上下文的物件     經理和有方法,如     * geturl() - 返回檢索到的資源的URL,常用於       確定是否遵循重定向     * info() - 返回頁面的元資訊,例如標題       email.message_from_string()例項的形式(請參閱快速參考       HTTP標頭)     * getcode() - 返回響應的HTTP狀態程式碼。引發URLError       關於錯誤。     對於HTTP和HTTPS URL,此函式返回http.client.HTTPResponse     物件略有修改。除了以上三種新方法外,還有     msg屬性包含與reason屬性相同的資訊---     伺服器返回的原因短語 - 而不是響應     在HTTPResponse的文件中指定的標頭。     對於遺留顯式處理的FTP,檔案和資料URL以及請求     URLopener和FancyURLopener類,這個函式返回一個     urllib.response.addinfourl物件。 """
View Code

3.request中urlopen的post請求分析

"""urlopen的post請求分析"""
from urllib import parse
from urllib import request
import json


# 轉換utf8編碼的data資料
data = bytes(parse.urlencode({"word": "hello"}), encoding="utf8")
# parse.urlencode({"word": "hello"})    返回字串形式'word=hello'
print(data)       # b'word=hello'    返回bytes型別資料與下面json區別
print(type(data))    # <class 'bytes'>
res = request.urlopen("http://httpbin.org/post", data=data)
print(res)          # <http.client.HTTPResponse object at 0x00000184DB1C3E10>   返回響應物件
print(type(res))    # <class 'http.client.HTTPResponse'>   物件型別
print(res.read())   # 讀取返回的內容中b'"form":{"word":"hello"},'此欄位表明模擬了表單提交的方式
arg = json.dumps({"word": "hello"})
print(arg)          # '{"word": "hello"}' json返回字串形式字典資料
print(type(arg))    # <class 'str'>
View Code

4.request中urlopen的異常處理

"""urllib的異常處理"""
from urllib import request, error


try:
    res = request.urlopen("https://home.cnblogs.com/u/Guishuzhe/1")
except error.HTTPError as e:
    # 先捕獲子類詳細異常原因
    print(e.reason, e.code, e.headers)
except error.URLError as e:
    # 再用父類捕獲子類中沒有的異常
    print(e.reason)
else:
    print("Request Successfully")



import socket
from urllib import request
from urllib import error


try:
    # 設定超時時間timeout=0.2
    res = request.urlopen("http://httpbin.org/get", timeout=0.2)
# 捕捉超時異常,返回友好資訊
except error.URLError as e:
    print(type(e.reason))
    # class URLError(OSError):原始碼  self.reason屬性, e.reason呼叫這個屬性
    # 內建函式isinstance判斷錯誤物件是不是某一型別
    # 在這裡是連線超時錯誤socket.timeout
    if isinstance(e.reason, socket.timeout):
        print("超時了")
View Code

5.urllib進階設定Handler

"""urllib進階設定Handler工具"""
from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener
from urllib.error import URLError


username = "username"
password = "password"
url = "http://127.0.0.1:8000/"
# 例項化一個待處理物件
p = HTTPPasswordMgrWithDefaultRealm()
# 給例項化物件新增請求引數realm=None等..
p.add_password(None, url, username, password)
# class AbstractBasicAuthHandler:找到父類並例項化出具體請求物件(Handler)
auth_handler = HTTPBasicAuthHandler(p)
# build_opener()方法接受*Handlers任意個Handler物件進行去重等處理,返回Opener物件
opener = build_opener(auth_handler)

try:
    # 開始請求
    res = opener.open(url)
    # 獲取請求結果
    html = res.read().decode("utf8")
    print(html)
except URLError as e:
    # 列印錯誤資訊
    print(e.reason)


"""
HITPDefaultErrorHandler :用於處理HTTP響應錯誤,錯誤都會丟擲HTTPError型別的異常
HTTPRedirectHandler :用於處理重定向
HTTPCookieProcessor 用於處理Cookies
ProxyHandler :用於設定代理預設代理為空
HπPPasswordMgr :用於管理密碼,它維護了使用者名稱和密碼的表
HTTPBasicAuthHandler 用於管理認證,如果一個連結開啟時需要認證,那麼可以用它來解決認證問題
"""
View Code

6.cookies的處理

"""cookies的處理"""
from http import cookiejar
from urllib import request


# 存放cookie資訊
filename = "cookies.txt"
cookie = cookiejar.LWPCookieJar(filename)    # 建議使用此儲存格式
# cookie = cookiejar.MozillaCookieJar(filename)
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler)
res = opener.open("http://www.baidu.com")
cookie.save(ignore_discard=True, ignore_expires=True)



# 讀取cookie資訊
cookie = cookiejar.LWPCookieJar()       # 例項化LWP物件
# 指定要讀取的檔案資料到cookie例項,忽略丟棄和忽略過期
cookie.load("cookies.txt", ignore_discard=True, ignore_expires=True)
# 將讀取的cookie資訊封裝為handler型別
handler = request.HTTPCookieProcessor(cookie)
# 建立一個opener物件
opener = request.build_opener(handler)
# 呼叫opener物件的open方法開啟url
res = opener.open("http://www.baidu.com")
print(res.read().decode("utf-8"))
View Code

7.代理設定

"""urllib的代理設定"""
from urllib.error import URLError
from urllib.request import ProxyHandler, build_opener


# 設定代理請求的型別、ip和埠,_parse_proxy函式完成代理引數解析
proxy_handler = ProxyHandler({
    "http": "http://124.231.16.75:9000",
    "https": "https://113.105.201.193:3128"
})
# 封裝設定的代理資料,製造opener物件
opener = build_opener(proxy_handler)
try:
    # 呼叫opener的open方法代理訪問百度
    res = opener.open("https://www.baidu.com")
    print(res.read().decode("utf-8"))
except URLError as e:
    print(e.reason)
View Code