Python中urlopen()介紹


#以下介紹是基於Python3.4.3

一.  簡介

    urllib.request.urlopen()函數用於實現對目標url的訪問。

  函數原型如下:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) 

  函數定義如下:

def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
            *, cafile=None, capath=None, cadefault=False, context=None):
    global _opener
    if cafile or capath or cadefault:
        if context is not None:
            raise ValueError(
                "You can't pass both context and any of cafile, capath, and "
                "cadefault"
            )
        if not _have_ssl:
            raise ValueError('SSL support not available')
        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
                                             cafile=cafile,
                                             capath=capath)
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif context:
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif _opener is None:
        _opener = opener = build_opener()
    else:
        opener = _opener
    return opener.open(url, data, timeout)

二.  函數參數介紹

  <1>url 參數:目標資源在網路中的位置。可以是一個表示URL的字符串(如:http://www.xxxx.com/);也可以是一個urllib.request對象,詳細介紹請跳轉

  <2>data參數:data用來指明發往服務器請求中的額外的信息(如:在線翻譯,在線答題等提交的內容)。HTTP是python中實現的眾多網絡通信http、https、ftp等協議中,唯一一個             使用data 參數的,也就是說只有打開的是http網址的時候,自定義data參數才會有作用。另外,官方API手冊介紹指出:

            <2.1> data必須是一個字節數據對象(Python的bytes object)

     <2.2>data必須符合標准the standard application/x-www-form-urlencoded format,怎么得到這種標准結構的data呢?使用urllib.parse.urlencode()將自定義的data轉換成

         標准格式,而這個函數所能接收的參數類型是pyhon中的mapping object(鍵/值對,如dict) or a sequence of two-element tuples(元素是tuple的列表)。

     <2.3>data也可以是一個可迭代的對象,這種情況下就需要配置response對象中的Conten-length,指明data的大小。

     <2.4>data默認是None,此時以GET方式發送請求;當用戶給出data參數的時候,改為POST方式發送請求。

  <3>cafile、capath、cadefault 參數:用於實現可信任的CA證書的HTTP請求。(基本上很少用)

  <4>context參數:實現SSL加密傳輸。(基本上很少用)

三.  舉個栗子

  下面這個程序,實現了urlopen()函數的大部分功能,特別是data參數。data自定義,data格式轉換,數據的編碼encode()和解碼decode()。

 

#coding=utf-8
#Python3.4.3   OS:W7-32
'''
利用有道翻譯進行在線翻譯

'''
import urllib.request
import urllib.parse
import json

def traslate(words):
    #目標URL
    targetURL = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"

    #用戶自定義表單,words表示的是用戶要翻譯的內容。這里使用的是dict類型,也可以使用元組列表(已經試過的)。
    data = {}
    data['type'] = 'AUTO'
    data['i'] = words
    data['doctype'] = 'json'
    data['xmlVersion'] = '1.8'
    data['keyfrom'] = 'fanyi.web'
    data['ue'] = 'UTF-8'
    data['action'] = 'FY_BY_CLICKBUTTON'
    data['typoResult'] = 'true'

    #將自定義data轉換成標准格式
    data = urllib.parse.urlencode(data).encode('utf-8')

    #發送用戶請求
    html = urllib.request.urlopen(targetURL, data)

    #讀取並解碼內容
    rst = html.read().decode("utf-8")
    rst_dict = json.loads(rst)

    return rst_dict['translateResult'][0][0]['tgt']

if __name__ == "__main__":
    print("輸入字母q表示退出")
    while True:
        words = input("請輸入要查詢的單詞或句子:\n")
        if words == 'q':
            break
        result = traslate(words)
        print("翻譯結果是:%s"%result)

 ~~~~有待改進,希望大家提出寶貴意見,一同學習。

=======================================================================================================

參考來源:《小甲魚零基礎入門學Python》這個視頻講的超好,詼諧幽默,又詳細。

     官方文檔:https://docs.python.org/3/


免責聲明!

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



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