日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python學習之urllib

系統 1841 0

這里寫自定義目錄標題

  • 閱讀目錄
    • urllib.request.urlopen()
      • 請求示例程序
      • urlopen()提供的返回值方法
      • urlopen()傳遞data參數
      • urlopen()傳遞timeout參數

閱讀目錄

urllib是python內置的HTTP請求庫,無需安裝即可使用,它包含了4個模塊:

request:它是最基本的http請求模塊,用來模擬發送請求

error:異常處理模塊,如果出現錯誤可以捕獲這些異常

parse:一個工具模塊,提供了許多URL處理方法,如:拆分、解析、合并等

robotparser:主要用來識別網站的robots.txt文件,然后判斷哪些網站可以爬
Python學習之urllib_第1張圖片

urllib.request.urlopen()

            
              urlopen
              
                (
              
              url
              
                ,
              
               data
              
                =
              
              
                None
              
              
                ,
              
               timeout
              
                =
              
              socket
              
                .
              
              _GLOBAL_DEFAULT_TIMEOUT
              
                ,
              
              
                *
              
              
                ,
              
               cafile
              
                =
              
              
                None
              
              
                ,
              
               capath
              
                =
              
              
                None
              
              
                ,
              
               cadefault
              
                =
              
              
                False
              
              
                ,
              
               context
              
                =
              
              
                None
              
              
                )
              
            
          
  1. url:請求地址
  2. data: Post請求提交的數據
  3. timeout: 超時時間
  4. cafile:這個是CA證書
  5. capath :這個是CA證書路徑
  6. cadefault=False:默認沒有CA證書
  7. context: 這個可以指定SSL安裝驗證設置,比如我們可以設置忽略證書驗證等等。

請求示例程序

            
              
                import
              
               urllib
              
                .
              
              request


              
                """

urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,*
           ,cafile=None, capath=None, cadefault=False, context=None)

"""
              
              
resopnse
              
                =
              
              urllib
              
                .
              
              request
              
                .
              
              urlopen
              
                (
              
              
                "https://www.python.org"
              
              
                )
              
            
          

urlopen()提供的返回值方法

  1. read(): 對HTTPResponse類型數據進行操作
            
              
                print
              
              
                (
              
              
                type
              
              
                (
              
              resopnse
              
                )
              
              
                )
              
              
                ### 
                
              
              
                #讀取數據,編碼UTF-8
              
              
                print
              
              
                (
              
              resopnse
              
                .
              
              read
              
                (
              
              
                )
              
              
                .
              
              decode
              
                (
              
              
                'UTF-8'
              
              
                )
              
              
                )
              
            
          

Python學習之urllib_第2張圖片

  1. status 狀態嗎
  2. getheaders() 頭信息
  3. getheader(‘param’) 獲取指定的頭信息
            
              
                print
              
              
                (
              
              resopnse
              
                .
              
              status
              
                )
              
              
                # 狀態碼
              
              
                print
              
              
                (
              
              resopnse
              
                .
              
              getheaders
              
                (
              
              
                )
              
              
                )
              
              
                # 頭信息
              
              
                """
[   ('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), 
    ('X-Frame-Options', 'DENY'), ('Via', '1.1 vegur'), ('Via', '1.1 varnish'), 
    ('Content-Length', '48914'), ('Accept-Ranges', 'bytes'), 
    ('Date', 'Mon, 16 Sep 2019 13:55:27 GMT'), ('Via', '1.1 varnish'), 
    ('Age', '2874'), ('Connection', 'close'), 
    ('X-Served-By', 'cache-iad2127-IAD, cache-lax8634-LAX'), 
    ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '1, 99'), 
    ('X-Timer', 'S1568642127.467226,VS0,VE0'), ('Vary', 'Cookie'), 
    ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]

"""
              
              
                print
              
              
                (
              
              resopnse
              
                .
              
              getheader
              
                (
              
              
                'Server'
              
              
                )
              
              
                )
              
              
                # 獲取服務器類型 nginx
              
            
          

urlopen()傳遞data參數

            
              data
              
                =
              
              
                bytes
              
              
                (
              
              urllib
              
                .
              
              parse
              
                .
              
              urlencode
              
                (
              
              
                {
              
              
                'word'
              
              
                :
              
              
                'hello'
              
              
                }
              
              
                )
              
              
                ,
              
              encoding
              
                =
              
              
                'UTF-8'
              
              
                )
              
              
resopnse
              
                =
              
              urllib
              
                .
              
              request
              
                .
              
              urlopen
              
                (
              
              
                'http://httpbin.org/post'
              
              
                ,
              
              data
              
                =
              
              data
              
                )
              
              
                print
              
              
                (
              
              resopnse
              
                .
              
              read
              
                (
              
              
                )
              
              
                )
              
            
          

規定data參數是byte類型。因此我們需要將參數轉化為byte.調用byte()方法。第一個參數是String類型。第二個參數為編碼。我們傳遞一個key為word,value為hello的參數。使用urllib.parse.urlencode將字典轉化為string類型。最終返回的結果如下:

注意,傳遞data參數則必須是POST請求

            
              
                {
              
              
                "args"
              
              
                :
              
              
                {
              
              
                }
              
              
                ,
              
              
                "data"
              
              
                :
              
              
                ""
              
              
                ,
              
              
                "files"
              
              
                :
              
              
                {
              
              
                }
              
              
                ,
              
              
                "form"
              
              
                :
              
              
                {
              
              
                "word"
              
              
                :
              
              
                "hello"
              
              
                }
              
              
                ,
              
              
                "headers"
              
              
                :
              
              
                {
              
              
                "Accept-Encoding"
              
              
                :
              
              
                "identity"
              
              
                ,
              
              
                "Content-Length"
              
              
                :
              
              
                "10"
              
              
                ,
              
              
                "Content-Type"
              
              
                :
              
              
                "application/x-www-form-urlencoded"
              
              
                ,
              
              
                "Host"
              
              
                :
              
              
                "httpbin.org"
              
              
                ,
              
              
                "User-Agent"
              
              
                :
              
              
                "Python-urllib/3.5"
              
              
                }
              
              
                ,
              
              
                "json"
              
              
                :
              
              
                null
              
              
                ,
              
              
                "origin"
              
              
                :
              
              
                "117.176.186.251, 117.176.186.251"
              
              
                ,
              
              
                "url"
              
              
                :
              
              
                "https://httpbin.org/post"
              
              
                }
              
            
          

可以看到我們的參數在form里面,因此作為表單去提交參數的。

urlopen()傳遞timeout參數

            
              resopnse
              
                =
              
              urllib
              
                .
              
              request
              
                .
              
              urlopen
              
                (
              
              
                'http://httpbin.org/post'
              
              
                ,
              
              data
              
                =
              
              data
              
                ,
              
              timeout
              
                =
              
              
                1
              
              
                )
              
            
          
            
                File "/usr/lib/python3.5/http/client.py", line 1198, in getresponse
    response.begin()
  File "/usr/lib/python3.5/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.5/http/client.py", line 258, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.5/socket.py", line 576, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

            
          

設置1s超時時間,請求socket超時!

            
              
                print
              
              
                (
              
              
                "********************************"
              
              
                )
              
              
data
              
                =
              
              
                bytes
              
              
                (
              
              urllib
              
                .
              
              parse
              
                .
              
              urlencode
              
                (
              
              
                {
              
              
                'word'
              
              
                :
              
              
                'hello'
              
              
                }
              
              
                )
              
              
                ,
              
              encoding
              
                =
              
              
                'UTF-8'
              
              
                )
              
              
                try
              
              
                :
              
              
    resopnse
              
                =
              
              urllib
              
                .
              
              request
              
                .
              
              urlopen
              
                (
              
              
                'http://httpbin.org/post'
              
              
                ,
              
              data
              
                =
              
              data
              
                ,
              
              timeout
              
                =
              
              
                0.1
              
              
                )
              
              
                except
              
               urllib
              
                .
              
              error
              
                .
              
              URLError 
              
                as
              
               e
              
                :
              
              
                print
              
              
                (
              
              
                'TIME OUT'
              
              
                )
              
              
                print
              
              
                (
              
              resopnse
              
                .
              
              read
              
                (
              
              
                )
              
              
                )
              
            
          

更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 肃宁县| 寿宁县| 故城县| 德钦县| 平顺县| 桂阳县| 米易县| 阜阳市| 东安县| 平潭县| 长汀县| 维西| 丽江市| 五莲县| 淄博市| 黑龙江省| 宁乡县| 兴安盟| 茌平县| 柳江县| 横山县| 葵青区| 成武县| 弋阳县| 阳朔县| 云浮市| 灵山县| 武宣县| 合山市| 桂阳县| 临泉县| 通化市| 铁岭市| 山阴县| 会宁县| 波密县| 休宁县| 克山县| 阳山县| 乐安县| 佛教|